0
# Cleanup Management
1
2
Control automatic cleanup behavior and access to the system temporary directory for comprehensive temporary file lifecycle management.
3
4
## Capabilities
5
6
### Graceful Cleanup Setup
7
8
Enables automatic cleanup of all temporary objects created by tmp on process exit.
9
10
```javascript { .api }
11
/**
12
* Enables automatic cleanup of temporary objects on process exit
13
* This function should be called once at application startup
14
*/
15
function setGracefulCleanup();
16
```
17
18
**Usage Examples:**
19
20
```javascript
21
const tmp = require("tmp");
22
23
// Enable automatic cleanup at application startup
24
tmp.setGracefulCleanup();
25
26
// Now all temporary objects will be cleaned up automatically
27
tmp.file(function(err, path, fd, cleanupCallback) {
28
if (err) throw err;
29
30
console.log("Temp file:", path);
31
32
// No need to call cleanupCallback() - will happen automatically on exit
33
// But you can still call it manually for immediate cleanup
34
});
35
36
tmp.dir(function(err, path, cleanupCallback) {
37
if (err) throw err;
38
39
console.log("Temp directory:", path);
40
41
// Directory will be cleaned up automatically on process exit
42
});
43
44
// When the process exits (normally or via signals), all temp objects are removed
45
```
46
47
#### Graceful Cleanup Best Practices
48
49
```javascript
50
const tmp = require("tmp");
51
52
// Set up cleanup as early as possible in your application
53
tmp.setGracefulCleanup();
54
55
// Handle process signals explicitly if needed
56
process.on("SIGINT", function() {
57
console.log("Received SIGINT, cleaning up...");
58
// tmp will automatically clean up here
59
process.exit(0);
60
});
61
62
process.on("SIGTERM", function() {
63
console.log("Received SIGTERM, cleaning up...");
64
// tmp will automatically clean up here
65
process.exit(0);
66
});
67
68
// Clean shutdown in async contexts
69
async function gracefulShutdown() {
70
console.log("Starting graceful shutdown...");
71
72
// Do application cleanup...
73
74
// tmp cleanup happens automatically
75
process.exit(0);
76
}
77
78
// Register shutdown handler
79
process.on("SIGINT", gracefulShutdown);
80
process.on("SIGTERM", gracefulShutdown);
81
```
82
83
### Temporary Directory Access
84
85
Access the current system temporary directory path.
86
87
```javascript { .api }
88
/**
89
* Property getter that returns the current temporary directory path
90
* Evaluates lazily from os.tmpdir() with realpath resolution
91
*/
92
tmp.tmpdir // string
93
```
94
95
**Usage Examples:**
96
97
```javascript
98
const tmp = require("tmp");
99
const path = require("path");
100
const fs = require("fs");
101
102
// Get the current temporary directory
103
console.log("System temp directory:", tmp.tmpdir);
104
// Example output: /tmp (Unix) or C:\Users\username\AppData\Local\Temp (Windows)
105
106
// Use for custom temporary file creation
107
const customTempFile = path.join(tmp.tmpdir, "my-custom-file.txt");
108
fs.writeFileSync(customTempFile, "Custom temp file content");
109
110
// Create subdirectory structure in temp dir
111
const appTempDir = path.join(tmp.tmpdir, "myapp");
112
fs.mkdirSync(appTempDir, { recursive: true });
113
114
const configFile = path.join(appTempDir, "config.json");
115
fs.writeFileSync(configFile, JSON.stringify({ version: "1.0" }));
116
117
// Use with other libraries that need temp directory
118
const archivePath = path.join(tmp.tmpdir, "archive.zip");
119
// ... create archive using external library
120
121
// Check available space in temp directory
122
try {
123
const stats = fs.statSync(tmp.tmpdir);
124
console.log("Temp directory exists:", stats.isDirectory());
125
} catch (err) {
126
console.error("Temp directory access error:", err.message);
127
}
128
```
129
130
#### Cross-Platform Temporary Directory Handling
131
132
```javascript
133
const tmp = require("tmp");
134
const path = require("path");
135
const fs = require("fs");
136
137
function createPortableTempPath(filename) {
138
// tmp.tmpdir handles cross-platform differences automatically
139
return path.join(tmp.tmpdir, filename);
140
}
141
142
// Works on Windows, macOS, and Linux
143
const logFile = createPortableTempPath("app.log");
144
const dataDir = createPortableTempPath("data");
145
146
console.log("Log file path:", logFile);
147
console.log("Data directory path:", dataDir);
148
149
// Create cross-platform temp structure
150
fs.mkdirSync(dataDir, { recursive: true });
151
fs.writeFileSync(logFile, "Application started\n");
152
153
// Temp directory is resolved to real path, handling symlinks
154
console.log("Resolved temp directory:", tmp.tmpdir);
155
```
156
157
### Manual Cleanup Strategies
158
159
Even with graceful cleanup enabled, you may want manual control over cleanup timing:
160
161
#### Immediate Cleanup
162
163
```javascript
164
const tmp = require("tmp");
165
166
// Enable graceful cleanup
167
tmp.setGracefulCleanup();
168
169
tmp.file(function(err, path, fd, cleanupCallback) {
170
if (err) throw err;
171
172
// Use the file immediately
173
const fs = require("fs");
174
fs.writeSync(fd, "Temporary data");
175
176
// Clean up immediately when done
177
cleanupCallback();
178
179
console.log("File cleaned up immediately");
180
});
181
```
182
183
#### Conditional Cleanup
184
185
```javascript
186
const tmp = require("tmp");
187
188
tmp.setGracefulCleanup();
189
190
function processFile(keepOnError = false) {
191
return new Promise((resolve, reject) => {
192
tmp.file(function(err, path, fd, cleanupCallback) {
193
if (err) return reject(err);
194
195
try {
196
// Process the file
197
const fs = require("fs");
198
fs.writeSync(fd, "Processing data...");
199
200
// Simulate processing that might fail
201
if (Math.random() < 0.3) {
202
throw new Error("Processing failed");
203
}
204
205
// Success - clean up
206
cleanupCallback();
207
resolve("Processing completed");
208
209
} catch (error) {
210
if (keepOnError) {
211
console.log("Keeping temp file for debugging:", path);
212
// Don't call cleanupCallback - file will be cleaned up on exit
213
} else {
214
cleanupCallback();
215
}
216
reject(error);
217
}
218
});
219
});
220
}
221
222
// Usage
223
processFile(true) // Keep files on error for debugging
224
.then(result => console.log(result))
225
.catch(err => console.error("Processing failed:", err.message));
226
```
227
228
#### Cleanup Coordination
229
230
```javascript
231
const tmp = require("tmp");
232
233
tmp.setGracefulCleanup();
234
235
class TempResourceManager {
236
constructor() {
237
this.resources = [];
238
}
239
240
createTempFile(options = {}) {
241
return new Promise((resolve, reject) => {
242
tmp.file(options, (err, path, fd, cleanupCallback) => {
243
if (err) return reject(err);
244
245
const resource = { path, fd, cleanup: cleanupCallback };
246
this.resources.push(resource);
247
resolve(resource);
248
});
249
});
250
}
251
252
createTempDir(options = {}) {
253
return new Promise((resolve, reject) => {
254
tmp.dir(options, (err, path, cleanupCallback) => {
255
if (err) return reject(err);
256
257
const resource = { path, cleanup: cleanupCallback };
258
this.resources.push(resource);
259
resolve(resource);
260
});
261
});
262
}
263
264
cleanupAll() {
265
this.resources.forEach(resource => {
266
try {
267
resource.cleanup();
268
} catch (err) {
269
console.error("Cleanup error:", err.message);
270
}
271
});
272
this.resources = [];
273
}
274
275
cleanupResource(resourcePath) {
276
const index = this.resources.findIndex(r => r.path === resourcePath);
277
if (index >= 0) {
278
const resource = this.resources[index];
279
resource.cleanup();
280
this.resources.splice(index, 1);
281
}
282
}
283
}
284
285
// Usage
286
const manager = new TempResourceManager();
287
288
async function doWork() {
289
const file1 = await manager.createTempFile({ prefix: "work1-" });
290
const file2 = await manager.createTempFile({ prefix: "work2-" });
291
const dir1 = await manager.createTempDir({ prefix: "workspace-" });
292
293
// Do work with temporary resources...
294
295
// Clean up specific resource
296
manager.cleanupResource(file1.path);
297
298
// Clean up all remaining resources
299
manager.cleanupAll();
300
}
301
302
doWork().catch(console.error);
303
```
304
305
### Cleanup Options and Behavior
306
307
#### Keep Option
308
309
Use the `keep` option to prevent automatic cleanup:
310
311
```javascript
312
const tmp = require("tmp");
313
314
tmp.setGracefulCleanup();
315
316
// This file will NOT be cleaned up automatically
317
tmp.file({ keep: true }, function(err, path, fd, cleanupCallback) {
318
if (err) throw err;
319
320
console.log("Persistent temp file:", path);
321
322
// Manual cleanup still works
323
// cleanupCallback();
324
325
// File will persist even after process exit
326
});
327
```
328
329
#### Error Handling in Cleanup
330
331
```javascript
332
const tmp = require("tmp");
333
334
tmp.setGracefulCleanup();
335
336
tmp.file(function(err, path, fd, cleanupCallback) {
337
if (err) throw err;
338
339
// Cleanup with error handling
340
cleanupCallback(function(cleanupErr) {
341
if (cleanupErr) {
342
console.error("Failed to clean up temp file:", cleanupErr.message);
343
} else {
344
console.log("Temp file cleaned up successfully");
345
}
346
});
347
});
348
```
349
350
**Important Notes:**
351
352
- `setGracefulCleanup()` should be called once at application startup
353
- Graceful cleanup handles process exit, SIGINT, SIGTERM, and uncaught exceptions
354
- Manual cleanup via callbacks always works, even with graceful cleanup enabled
355
- The `tmp.tmpdir` property is evaluated lazily and may change during application runtime
356
- Cleanup operations are synchronous and block the exit process briefly
357
- Files/directories with `keep: true` are never automatically cleaned up
358
- Failed cleanup operations are logged but don't prevent process exit