Temporary file and directory creator for Node.js applications
—
Control automatic cleanup behavior and access to the system temporary directory for comprehensive temporary file lifecycle management.
Enables automatic cleanup of all temporary objects created by tmp on process exit.
/**
* Enables automatic cleanup of temporary objects on process exit
* This function should be called once at application startup
*/
function setGracefulCleanup();Usage Examples:
const tmp = require("tmp");
// Enable automatic cleanup at application startup
tmp.setGracefulCleanup();
// Now all temporary objects will be cleaned up automatically
tmp.file(function(err, path, fd, cleanupCallback) {
if (err) throw err;
console.log("Temp file:", path);
// No need to call cleanupCallback() - will happen automatically on exit
// But you can still call it manually for immediate cleanup
});
tmp.dir(function(err, path, cleanupCallback) {
if (err) throw err;
console.log("Temp directory:", path);
// Directory will be cleaned up automatically on process exit
});
// When the process exits (normally or via signals), all temp objects are removedconst tmp = require("tmp");
// Set up cleanup as early as possible in your application
tmp.setGracefulCleanup();
// Handle process signals explicitly if needed
process.on("SIGINT", function() {
console.log("Received SIGINT, cleaning up...");
// tmp will automatically clean up here
process.exit(0);
});
process.on("SIGTERM", function() {
console.log("Received SIGTERM, cleaning up...");
// tmp will automatically clean up here
process.exit(0);
});
// Clean shutdown in async contexts
async function gracefulShutdown() {
console.log("Starting graceful shutdown...");
// Do application cleanup...
// tmp cleanup happens automatically
process.exit(0);
}
// Register shutdown handler
process.on("SIGINT", gracefulShutdown);
process.on("SIGTERM", gracefulShutdown);Access the current system temporary directory path.
/**
* Property getter that returns the current temporary directory path
* Evaluates lazily from os.tmpdir() with realpath resolution
*/
tmp.tmpdir // stringUsage Examples:
const tmp = require("tmp");
const path = require("path");
const fs = require("fs");
// Get the current temporary directory
console.log("System temp directory:", tmp.tmpdir);
// Example output: /tmp (Unix) or C:\Users\username\AppData\Local\Temp (Windows)
// Use for custom temporary file creation
const customTempFile = path.join(tmp.tmpdir, "my-custom-file.txt");
fs.writeFileSync(customTempFile, "Custom temp file content");
// Create subdirectory structure in temp dir
const appTempDir = path.join(tmp.tmpdir, "myapp");
fs.mkdirSync(appTempDir, { recursive: true });
const configFile = path.join(appTempDir, "config.json");
fs.writeFileSync(configFile, JSON.stringify({ version: "1.0" }));
// Use with other libraries that need temp directory
const archivePath = path.join(tmp.tmpdir, "archive.zip");
// ... create archive using external library
// Check available space in temp directory
try {
const stats = fs.statSync(tmp.tmpdir);
console.log("Temp directory exists:", stats.isDirectory());
} catch (err) {
console.error("Temp directory access error:", err.message);
}const tmp = require("tmp");
const path = require("path");
const fs = require("fs");
function createPortableTempPath(filename) {
// tmp.tmpdir handles cross-platform differences automatically
return path.join(tmp.tmpdir, filename);
}
// Works on Windows, macOS, and Linux
const logFile = createPortableTempPath("app.log");
const dataDir = createPortableTempPath("data");
console.log("Log file path:", logFile);
console.log("Data directory path:", dataDir);
// Create cross-platform temp structure
fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(logFile, "Application started\n");
// Temp directory is resolved to real path, handling symlinks
console.log("Resolved temp directory:", tmp.tmpdir);Even with graceful cleanup enabled, you may want manual control over cleanup timing:
const tmp = require("tmp");
// Enable graceful cleanup
tmp.setGracefulCleanup();
tmp.file(function(err, path, fd, cleanupCallback) {
if (err) throw err;
// Use the file immediately
const fs = require("fs");
fs.writeSync(fd, "Temporary data");
// Clean up immediately when done
cleanupCallback();
console.log("File cleaned up immediately");
});const tmp = require("tmp");
tmp.setGracefulCleanup();
function processFile(keepOnError = false) {
return new Promise((resolve, reject) => {
tmp.file(function(err, path, fd, cleanupCallback) {
if (err) return reject(err);
try {
// Process the file
const fs = require("fs");
fs.writeSync(fd, "Processing data...");
// Simulate processing that might fail
if (Math.random() < 0.3) {
throw new Error("Processing failed");
}
// Success - clean up
cleanupCallback();
resolve("Processing completed");
} catch (error) {
if (keepOnError) {
console.log("Keeping temp file for debugging:", path);
// Don't call cleanupCallback - file will be cleaned up on exit
} else {
cleanupCallback();
}
reject(error);
}
});
});
}
// Usage
processFile(true) // Keep files on error for debugging
.then(result => console.log(result))
.catch(err => console.error("Processing failed:", err.message));const tmp = require("tmp");
tmp.setGracefulCleanup();
class TempResourceManager {
constructor() {
this.resources = [];
}
createTempFile(options = {}) {
return new Promise((resolve, reject) => {
tmp.file(options, (err, path, fd, cleanupCallback) => {
if (err) return reject(err);
const resource = { path, fd, cleanup: cleanupCallback };
this.resources.push(resource);
resolve(resource);
});
});
}
createTempDir(options = {}) {
return new Promise((resolve, reject) => {
tmp.dir(options, (err, path, cleanupCallback) => {
if (err) return reject(err);
const resource = { path, cleanup: cleanupCallback };
this.resources.push(resource);
resolve(resource);
});
});
}
cleanupAll() {
this.resources.forEach(resource => {
try {
resource.cleanup();
} catch (err) {
console.error("Cleanup error:", err.message);
}
});
this.resources = [];
}
cleanupResource(resourcePath) {
const index = this.resources.findIndex(r => r.path === resourcePath);
if (index >= 0) {
const resource = this.resources[index];
resource.cleanup();
this.resources.splice(index, 1);
}
}
}
// Usage
const manager = new TempResourceManager();
async function doWork() {
const file1 = await manager.createTempFile({ prefix: "work1-" });
const file2 = await manager.createTempFile({ prefix: "work2-" });
const dir1 = await manager.createTempDir({ prefix: "workspace-" });
// Do work with temporary resources...
// Clean up specific resource
manager.cleanupResource(file1.path);
// Clean up all remaining resources
manager.cleanupAll();
}
doWork().catch(console.error);Use the keep option to prevent automatic cleanup:
const tmp = require("tmp");
tmp.setGracefulCleanup();
// This file will NOT be cleaned up automatically
tmp.file({ keep: true }, function(err, path, fd, cleanupCallback) {
if (err) throw err;
console.log("Persistent temp file:", path);
// Manual cleanup still works
// cleanupCallback();
// File will persist even after process exit
});const tmp = require("tmp");
tmp.setGracefulCleanup();
tmp.file(function(err, path, fd, cleanupCallback) {
if (err) throw err;
// Cleanup with error handling
cleanupCallback(function(cleanupErr) {
if (cleanupErr) {
console.error("Failed to clean up temp file:", cleanupErr.message);
} else {
console.log("Temp file cleaned up successfully");
}
});
});Important Notes:
setGracefulCleanup() should be called once at application startuptmp.tmpdir property is evaluated lazily and may change during application runtimekeep: true are never automatically cleaned upInstall with Tessl CLI
npx tessl i tessl/npm-tmp