Temporary files and directories with secure permissions and automatic cleanup
npx @tessl/cli install tessl/npm-temp@0.9.00
# temp
1
2
A secure Node.js library for creating and managing temporary files, directories, and streams with automatic cleanup functionality. The temp package provides both synchronous and asynchronous APIs with configurable prefixes, suffixes, and automatic cleanup on process exit.
3
4
## Package Information
5
6
- **Package Name**: temp
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install temp`
10
11
## Core Imports
12
13
```javascript
14
const temp = require('temp');
15
```
16
17
For individual imports:
18
19
```javascript
20
const { open, mkdir, track, cleanup } = require('temp');
21
```
22
23
## Basic Usage
24
25
```javascript
26
const temp = require('temp');
27
28
// Enable automatic cleanup on process exit
29
temp.track();
30
31
// Create a temporary file
32
temp.open('myprefix', (err, info) => {
33
if (err) throw err;
34
console.log('Temporary file:', info.path);
35
console.log('File descriptor:', info.fd);
36
37
// Use the file...
38
const fs = require('fs');
39
fs.writeSync(info.fd, 'Hello, temporary world!');
40
fs.closeSync(info.fd);
41
});
42
43
// Create a temporary directory
44
temp.mkdir('mydir', (err, dirPath) => {
45
if (err) throw err;
46
console.log('Temporary directory:', dirPath);
47
48
// Use the directory...
49
});
50
```
51
52
## Architecture
53
54
The temp package is built around several key concepts:
55
56
- **Security First**: All temporary files created with 0600 permissions (owner read/write only), directories with 0700 permissions
57
- **Unique Naming**: Names generated using timestamps, process IDs, and random values to prevent collisions
58
- **Optional Tracking**: Automatic cleanup on process exit when tracking is enabled
59
- **Dual APIs**: Synchronous and asynchronous versions of all creation functions
60
- **Flexible Configuration**: Support for custom prefixes, suffixes, and directories
61
62
## Capabilities
63
64
### Tracking and Cleanup
65
66
Control automatic cleanup behavior for temporary resources.
67
68
```javascript { .api }
69
/**
70
* Enable or disable tracking for automatic cleanup on process exit
71
* @param {boolean} [value=true] - Enable (true) or disable (false) tracking
72
* @returns {Object} temp module (chainable)
73
*/
74
temp.track(value);
75
76
/**
77
* Asynchronously clean up all tracked temporary files and directories
78
* @param {Function} [callback] - Callback function(err, stats)
79
* @returns {Promise<{files: number, dirs: number}>} Cleanup statistics if no callback
80
*/
81
temp.cleanup(callback);
82
83
/**
84
* Synchronously clean up all tracked temporary files and directories
85
* @returns {{files: number, dirs: number}|false} Cleanup statistics or false if not tracking
86
*/
87
temp.cleanupSync();
88
89
/**
90
* The system temporary directory path used by the package
91
* @type {string}
92
*/
93
temp.dir;
94
```
95
96
**Usage Examples:**
97
98
```javascript
99
const temp = require('temp');
100
101
// Enable tracking (chainable)
102
temp.track();
103
104
// Or explicitly enable/disable
105
temp.track(true); // enable
106
temp.track(false); // disable
107
108
// Manual cleanup (async)
109
temp.cleanup((err, stats) => {
110
if (err) throw err;
111
console.log(`Cleaned up ${stats.files} files and ${stats.dirs} directories`);
112
});
113
114
// Manual cleanup (sync)
115
const stats = temp.cleanupSync();
116
console.log(`Cleaned up ${stats.files} files and ${stats.dirs} directories`);
117
118
// Check temp directory location
119
console.log('System temp directory:', temp.dir);
120
```
121
122
### Temporary Files
123
124
Create temporary files with exclusive access and secure permissions.
125
126
```javascript { .api }
127
/**
128
* Create a temporary file asynchronously with exclusive access (0600 permissions)
129
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
130
* @param {Function} [callback] - Callback function(err, info) where info = {path, fd}
131
* @returns {Promise<{path: string, fd: number}>} File info if no callback
132
*/
133
temp.open(affixes, callback);
134
135
/**
136
* Create a temporary file synchronously with exclusive access (0600 permissions)
137
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
138
* @returns {{path: string, fd: number}} File info with path and file descriptor
139
*/
140
temp.openSync(affixes);
141
142
/**
143
* Create a temporary write stream with exclusive access (0600 permissions)
144
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
145
* @returns {fs.WriteStream} WriteStream with additional 'path' property
146
*/
147
temp.createWriteStream(affixes);
148
```
149
150
**Usage Examples:**
151
152
```javascript
153
const temp = require('temp');
154
const fs = require('fs');
155
156
temp.track();
157
158
// Basic temporary file (async)
159
temp.open('myprefix', (err, info) => {
160
if (err) throw err;
161
162
fs.writeSync(info.fd, 'Hello World');
163
fs.closeSync(info.fd);
164
165
console.log('File created at:', info.path);
166
});
167
168
// With suffix and custom directory (sync)
169
const fileInfo = temp.openSync({
170
prefix: 'data-',
171
suffix: '.json',
172
dir: '/custom/temp/path'
173
});
174
175
fs.writeFileSync(fileInfo.path, JSON.stringify({hello: 'world'}));
176
fs.closeSync(fileInfo.fd);
177
178
// Using write stream
179
const stream = temp.createWriteStream({prefix: 'log-', suffix: '.txt'});
180
stream.write('Log entry 1\n');
181
stream.write('Log entry 2\n');
182
stream.end();
183
184
console.log('Stream file created at:', stream.path);
185
```
186
187
### Temporary Directories
188
189
Create temporary directories with secure permissions for organizing multiple temporary files.
190
191
```javascript { .api }
192
/**
193
* Create a temporary directory asynchronously with secure permissions (0700)
194
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
195
* @param {Function} [callback] - Callback function(err, dirPath)
196
* @returns {Promise<string>} Directory path if no callback
197
*/
198
temp.mkdir(affixes, callback);
199
200
/**
201
* Create a temporary directory synchronously with secure permissions (0700)
202
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
203
* @returns {string} Directory path
204
*/
205
temp.mkdirSync(affixes);
206
```
207
208
**Usage Examples:**
209
210
```javascript
211
const temp = require('temp');
212
const fs = require('fs');
213
const path = require('path');
214
215
temp.track();
216
217
// Basic temporary directory (async)
218
temp.mkdir('project-', (err, dirPath) => {
219
if (err) throw err;
220
221
// Create files within the temporary directory
222
const configFile = path.join(dirPath, 'config.json');
223
const dataFile = path.join(dirPath, 'data.txt');
224
225
fs.writeFileSync(configFile, JSON.stringify({debug: true}));
226
fs.writeFileSync(dataFile, 'Application data');
227
228
console.log('Project directory created at:', dirPath);
229
});
230
231
// Custom directory settings (sync)
232
const workDir = temp.mkdirSync({
233
prefix: 'build-',
234
suffix: '-workspace',
235
dir: '/tmp/myapp'
236
});
237
238
console.log('Work directory created at:', workDir);
239
```
240
241
### Path Generation
242
243
Generate unique temporary paths without creating files or directories.
244
245
```javascript { .api }
246
/**
247
* Generate a unique temporary path without creating the file or directory
248
* @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
249
* @returns {string} Generated temporary path
250
*/
251
temp.path(affixes);
252
```
253
254
**Usage Examples:**
255
256
```javascript
257
const temp = require('temp');
258
const fs = require('fs');
259
260
// Generate paths with different configurations
261
const tempFile = temp.path();
262
const pdfFile = temp.path({suffix: '.pdf'});
263
const dataFile = temp.path({prefix: 'data-', suffix: '.json'});
264
const customPath = temp.path({
265
prefix: 'backup-',
266
suffix: '.sql',
267
dir: '/custom/temp/location'
268
});
269
270
console.log('Generated paths:');
271
console.log('- Default:', tempFile);
272
console.log('- PDF:', pdfFile);
273
console.log('- Data:', dataFile);
274
console.log('- Custom:', customPath);
275
276
// Note: Files are not created automatically
277
// You must create them yourself and handle cleanup
278
fs.writeFileSync(pdfFile, 'PDF content here');
279
280
// Manual cleanup is required since temp.path() doesn't track files
281
fs.unlinkSync(pdfFile);
282
```
283
284
## Types
285
286
```javascript { .api }
287
/**
288
* File information returned by temp.open() and temp.openSync()
289
* @typedef {Object} FileInfo
290
* @property {string} path - Full path to the temporary file
291
* @property {number} fd - File descriptor for the opened file
292
*/
293
294
/**
295
* Cleanup statistics returned by cleanup operations
296
* @typedef {Object} CleanupStats
297
* @property {number} files - Number of files cleaned up
298
* @property {number} dirs - Number of directories cleaned up
299
*/
300
301
/**
302
* Affixes configuration for customizing temporary names
303
* @typedef {Object} AffixesConfig
304
* @property {string} [prefix] - String to prepend to generated name
305
* @property {string} [suffix] - String to append to generated name
306
* @property {string} [dir] - Custom directory (defaults to system temp)
307
*/
308
```
309
310
## Error Handling
311
312
Common error scenarios and handling patterns:
313
314
```javascript
315
const temp = require('temp');
316
317
// Handle file creation errors
318
temp.open('myprefix', (err, info) => {
319
if (err) {
320
if (err.code === 'EACCES') {
321
console.error('Permission denied accessing temp directory');
322
} else if (err.code === 'ENOSPC') {
323
console.error('No space left on device');
324
} else {
325
console.error('Failed to create temp file:', err.message);
326
}
327
return;
328
}
329
330
// Success handling...
331
});
332
333
// Cleanup errors (when not tracking)
334
temp.cleanup((err, stats) => {
335
if (err) {
336
if (err.message === 'not tracking') {
337
console.error('Cleanup failed: tracking is not enabled');
338
console.log('Enable tracking with temp.track()');
339
} else {
340
console.error('Cleanup error:', err.message);
341
}
342
return;
343
}
344
345
console.log('Cleanup successful:', stats);
346
});
347
```
348
349
## Security Features
350
351
- **File Permissions**: Files created with 0600 (owner read/write only)
352
- **Directory Permissions**: Directories created with 0700 (owner read/write/execute only)
353
- **Exclusive Creation**: Files created with O_EXCL flag to prevent race conditions
354
- **Unique Names**: Generated using timestamp, process ID, and random components
355
- **Automatic Cleanup**: Optional tracking prevents temporary file accumulation
356
357
## Default Naming
358
359
When no affixes are provided, temp uses these default prefixes:
360
361
- **Files** (`temp.open`, `temp.openSync`): `'f-'`
362
- **Directories** (`temp.mkdir`, `temp.mkdirSync`): `'d-'`
363
- **Streams** (`temp.createWriteStream`): `'s-'`
364
365
Generated names follow the pattern: `{prefix}{year}{month}{day}-{pid}-{random}{suffix}`