or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-tmp-promise

The tmp package with promises support and disposers.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/tmp-promise@3.0.x

To install, run

npx @tessl/cli install tessl/npm-tmp-promise@3.0.0

0

# tmp-promise

1

2

tmp-promise provides promise-based wrappers around the popular `tmp` library for creating temporary files and directories in Node.js environments. It extends the original tmp package by adding native Promise support through Node.js util.promisify, eliminating the need for callback-based APIs.

3

4

## Package Information

5

6

- **Package Name**: tmp-promise

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install tmp-promise`

10

11

## Core Imports

12

13

```javascript

14

const tmpPromise = require('tmp-promise');

15

```

16

17

ES Modules:

18

19

```javascript

20

import * as tmpPromise from 'tmp-promise';

21

// or destructured imports

22

import {

23

file, fileSync,

24

dir, dirSync,

25

withFile, withDir,

26

tmpName, tmpNameSync,

27

tmpdir, setGracefulCleanup

28

} from 'tmp-promise';

29

```

30

31

## Basic Usage

32

33

```javascript

34

import { file, withFile, dir, withDir } from 'tmp-promise';

35

36

// Create a temporary file

37

const { path, fd, cleanup } = await file();

38

// work with file here using fd or path

39

await cleanup();

40

41

// Automatic cleanup with disposer pattern

42

await withFile(async ({ path, fd }) => {

43

// work with file here

44

// automatic cleanup when function completes or throws

45

});

46

47

// Create a temporary directory

48

const { path: dirPath, cleanup: dirCleanup } = await dir();

49

// work with directory here

50

await dirCleanup();

51

52

// Automatic directory cleanup

53

await withDir(async ({ path }) => {

54

// work with directory here

55

// automatic cleanup when function completes or throws

56

});

57

```

58

59

## Capabilities

60

61

### Temporary File Creation

62

63

Create temporary files with promise-based API, supporting both manual cleanup and automatic disposal patterns.

64

65

```javascript { .api }

66

/**

67

* Creates a temporary file asynchronously

68

* @param options - Optional file creation options from tmp package

69

* @returns Promise resolving to FileResult

70

*/

71

function file(options?: FileOptions): Promise<FileResult>;

72

73

/**

74

* Creates a temporary file synchronously (re-exported from tmp)

75

* @param options - Optional file creation options from tmp package

76

* @returns Synchronous file result with name, fd, removeCallback

77

*/

78

function fileSync(options?: FileOptions): SyncFileResult;

79

80

/**

81

* Disposer pattern for temporary files with automatic cleanup

82

* @param fn - Function to execute with the temporary file

83

* @param options - Optional file creation options from tmp package

84

* @returns Promise resolving to the result of fn

85

*/

86

function withFile<T>(

87

fn: (result: FileResult) => Promise<T>,

88

options?: FileOptions

89

): Promise<T>;

90

91

interface FileResult {

92

/** Path to the temporary file */

93

path: string;

94

/** File descriptor for the temporary file */

95

fd: number;

96

/** Async cleanup function to remove the file */

97

cleanup(): Promise<void>;

98

}

99

```

100

101

### Temporary Directory Creation

102

103

Create temporary directories with promise-based API, including automatic cleanup capabilities.

104

105

```javascript { .api }

106

/**

107

* Creates a temporary directory asynchronously

108

* @param options - Optional directory creation options from tmp package

109

* @returns Promise resolving to DirectoryResult

110

*/

111

function dir(options?: DirOptions): Promise<DirectoryResult>;

112

113

/**

114

* Creates a temporary directory synchronously (re-exported from tmp)

115

* @param options - Optional directory creation options from tmp package

116

* @returns Synchronous directory result with name, removeCallback

117

*/

118

function dirSync(options?: DirOptions): SyncDirectoryResult;

119

120

/**

121

* Disposer pattern for temporary directories with automatic cleanup

122

* @param fn - Function to execute with the temporary directory

123

* @param options - Optional directory creation options from tmp package

124

* @returns Promise resolving to the result of fn

125

*/

126

function withDir<T>(

127

fn: (results: DirectoryResult) => Promise<T>,

128

options?: DirOptions

129

): Promise<T>;

130

131

interface DirectoryResult {

132

/** Path to the temporary directory */

133

path: string;

134

/** Async cleanup function to remove the directory */

135

cleanup(): Promise<void>;

136

}

137

```

138

139

### Temporary Name Generation

140

141

Generate unique temporary filenames without creating actual files.

142

143

```javascript { .api }

144

/**

145

* Generates a unique temporary filename asynchronously

146

* @param options - Optional name generation options from tmp package

147

* @returns Promise resolving to temporary filename path

148

*/

149

function tmpName(options?: TmpNameOptions): Promise<string>;

150

151

/**

152

* Generates a unique temporary filename synchronously (re-exported from tmp)

153

* @param options - Optional name generation options from tmp package

154

* @returns Temporary filename path

155

*/

156

function tmpNameSync(options?: TmpNameOptions): string;

157

```

158

159

### System Utilities

160

161

Utility functions for temporary directory management and cleanup configuration.

162

163

```javascript { .api }

164

/**

165

* Returns the system's default temporary directory (re-exported from tmp)

166

* @returns Path to system temp directory

167

*/

168

function tmpdir(): string;

169

170

/**

171

* Enables automatic cleanup of temporary files on process exit (re-exported from tmp)

172

*/

173

function setGracefulCleanup(): void;

174

```

175

176

## Synchronous Result Types

177

178

The synchronous functions return objects with different properties than their async counterparts:

179

180

```javascript { .api }

181

interface SyncFileResult {

182

/** Path to the temporary file */

183

name: string;

184

/** File descriptor for the temporary file */

185

fd: number;

186

/** Synchronous cleanup function to remove the file */

187

removeCallback(): void;

188

}

189

190

interface SyncDirectoryResult {

191

/** Path to the temporary directory */

192

name: string;

193

/** Synchronous cleanup function to remove the directory */

194

removeCallback(): void;

195

}

196

```

197

198

## Options

199

200

All file and directory creation functions accept optional configuration objects passed through to the underlying tmp package. The option types below are defined by the `tmp` package and imported by `tmp-promise`:

201

202

```javascript { .api }

203

interface FileOptions {

204

/** File mode/permissions (default: 0600) */

205

mode?: number;

206

/** Filename prefix (default: 'tmp-') */

207

prefix?: string;

208

/** Filename suffix (default: '.tmp') */

209

postfix?: string;

210

/** mkstemp-like filename template */

211

template?: string;

212

/** Directory for temporary file (default: system temp dir) */

213

dir?: string;

214

/** Number of retry attempts (default: 3) */

215

tries?: number;

216

/** Keep file on process exit (default: false) */

217

keep?: boolean;

218

/** Don't return file descriptor (default: false) */

219

discardDescriptor?: boolean;

220

/** Detach file descriptor from cleanup (default: false) */

221

detachDescriptor?: boolean;

222

}

223

224

interface DirOptions {

225

/** Directory mode/permissions (default: 0700) */

226

mode?: number;

227

/** Directory name prefix (default: 'tmp-') */

228

prefix?: string;

229

/** mkstemp-like directory template */

230

template?: string;

231

/** Parent directory for temporary dir (default: system temp dir) */

232

dir?: string;

233

/** Number of retry attempts (default: 3) */

234

tries?: number;

235

/** Keep directory on process exit (default: false) */

236

keep?: boolean;

237

/** Recursively remove directory even if not empty (default: false) */

238

unsafeCleanup?: boolean;

239

}

240

241

interface TmpNameOptions {

242

/** Filename prefix (default: 'tmp-') */

243

prefix?: string;

244

/** Filename suffix (default: '.tmp') */

245

postfix?: string;

246

/** mkstemp-like filename template */

247

template?: string;

248

/** Directory for temporary name (default: system temp dir) */

249

dir?: string;

250

/** Number of retry attempts (default: 3) */

251

tries?: number;

252

}

253

```

254

255

## Usage Examples

256

257

### Basic File Operations

258

259

```javascript

260

import { file, fileSync } from 'tmp-promise';

261

262

// Async file creation

263

const { path, fd, cleanup } = await file({

264

prefix: 'myapp-',

265

postfix: '.log'

266

});

267

268

// Write to the file

269

const fs = require('fs');

270

fs.writeSync(fd, 'Hello, world!');

271

272

// Clean up when done

273

await cleanup();

274

275

// Sync file creation

276

const syncResult = fileSync({ prefix: 'sync-' });

277

console.log('Sync file:', syncResult.name);

278

syncResult.removeCallback(); // manual cleanup

279

```

280

281

### Disposer Pattern Examples

282

283

```javascript

284

import { withFile, withDir } from 'tmp-promise';

285

import { promises as fs } from 'fs';

286

import path from 'path';

287

288

// File disposer - automatic cleanup

289

const result = await withFile(async ({ path: filePath, fd }) => {

290

// File is automatically cleaned up after this function

291

await fs.writeFile(filePath, 'Processing data...');

292

const content = await fs.readFile(filePath, 'utf8');

293

return content.length;

294

});

295

296

// Directory disposer - automatic cleanup

297

const fileCount = await withDir(async ({ path: dirPath }) => {

298

// Create some files

299

await fs.writeFile(path.join(dirPath, 'file1.txt'), 'data1');

300

await fs.writeFile(path.join(dirPath, 'file2.txt'), 'data2');

301

302

// Count files

303

const files = await fs.readdir(dirPath);

304

return files.length;

305

// Directory is automatically cleaned up here

306

});

307

```

308

309

### Name Generation

310

311

```javascript

312

import { tmpName, tmpNameSync } from 'tmp-promise';

313

314

// Generate unique filenames without creating files

315

const filename = await tmpName({

316

prefix: 'data-export-',

317

postfix: '.csv'

318

});

319

320

const syncFilename = tmpNameSync({

321

template: '/tmp/backup-XXXXXX.tar.gz'

322

});

323

```

324

325

### Error Handling

326

327

```javascript

328

import { withFile } from 'tmp-promise';

329

330

try {

331

await withFile(async ({ path, fd }) => {

332

// If this throws, cleanup still happens

333

throw new Error('Processing failed');

334

});

335

} catch (error) {

336

// File has been cleaned up even though function threw

337

console.error('Processing failed:', error.message);

338

}

339

```

340

341

### Graceful Cleanup

342

343

```javascript

344

import { setGracefulCleanup } from 'tmp-promise';

345

346

// Enable automatic cleanup on process exit

347

setGracefulCleanup();

348

349

// Now all temporary files/directories will be cleaned up

350

// even if the process exits unexpectedly

351

```