or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-temp

Temporary files and directories with secure permissions and automatic cleanup

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/temp@0.9.x

To install, run

npx @tessl/cli install tessl/npm-temp@0.9.0

index.mddocs/

temp

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.

Package Information

  • Package Name: temp
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install temp

Core Imports

const temp = require('temp');

For individual imports:

const { open, mkdir, track, cleanup } = require('temp');

Basic Usage

const temp = require('temp');

// Enable automatic cleanup on process exit
temp.track();

// Create a temporary file
temp.open('myprefix', (err, info) => {
  if (err) throw err;
  console.log('Temporary file:', info.path);
  console.log('File descriptor:', info.fd);
  
  // Use the file...
  const fs = require('fs');
  fs.writeSync(info.fd, 'Hello, temporary world!');
  fs.closeSync(info.fd);
});

// Create a temporary directory
temp.mkdir('mydir', (err, dirPath) => {
  if (err) throw err;
  console.log('Temporary directory:', dirPath);
  
  // Use the directory...
});

Architecture

The temp package is built around several key concepts:

  • Security First: All temporary files created with 0600 permissions (owner read/write only), directories with 0700 permissions
  • Unique Naming: Names generated using timestamps, process IDs, and random values to prevent collisions
  • Optional Tracking: Automatic cleanup on process exit when tracking is enabled
  • Dual APIs: Synchronous and asynchronous versions of all creation functions
  • Flexible Configuration: Support for custom prefixes, suffixes, and directories

Capabilities

Tracking and Cleanup

Control automatic cleanup behavior for temporary resources.

/**
 * Enable or disable tracking for automatic cleanup on process exit
 * @param {boolean} [value=true] - Enable (true) or disable (false) tracking
 * @returns {Object} temp module (chainable)
 */
temp.track(value);

/**
 * Asynchronously clean up all tracked temporary files and directories
 * @param {Function} [callback] - Callback function(err, stats)
 * @returns {Promise<{files: number, dirs: number}>} Cleanup statistics if no callback
 */
temp.cleanup(callback);

/**
 * Synchronously clean up all tracked temporary files and directories
 * @returns {{files: number, dirs: number}|false} Cleanup statistics or false if not tracking
 */
temp.cleanupSync();

/**
 * The system temporary directory path used by the package
 * @type {string}
 */
temp.dir;

Usage Examples:

const temp = require('temp');

// Enable tracking (chainable)
temp.track();

// Or explicitly enable/disable
temp.track(true);  // enable
temp.track(false); // disable

// Manual cleanup (async)
temp.cleanup((err, stats) => {
  if (err) throw err;
  console.log(`Cleaned up ${stats.files} files and ${stats.dirs} directories`);
});

// Manual cleanup (sync)
const stats = temp.cleanupSync();
console.log(`Cleaned up ${stats.files} files and ${stats.dirs} directories`);

// Check temp directory location
console.log('System temp directory:', temp.dir);

Temporary Files

Create temporary files with exclusive access and secure permissions.

/**
 * Create a temporary file asynchronously with exclusive access (0600 permissions)
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @param {Function} [callback] - Callback function(err, info) where info = {path, fd}
 * @returns {Promise<{path: string, fd: number}>} File info if no callback
 */
temp.open(affixes, callback);

/**
 * Create a temporary file synchronously with exclusive access (0600 permissions)
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @returns {{path: string, fd: number}} File info with path and file descriptor
 */
temp.openSync(affixes);

/**
 * Create a temporary write stream with exclusive access (0600 permissions)
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @returns {fs.WriteStream} WriteStream with additional 'path' property
 */
temp.createWriteStream(affixes);

Usage Examples:

const temp = require('temp');
const fs = require('fs');

temp.track();

// Basic temporary file (async)
temp.open('myprefix', (err, info) => {
  if (err) throw err;
  
  fs.writeSync(info.fd, 'Hello World');
  fs.closeSync(info.fd);
  
  console.log('File created at:', info.path);
});

// With suffix and custom directory (sync)
const fileInfo = temp.openSync({
  prefix: 'data-',
  suffix: '.json',
  dir: '/custom/temp/path'
});

fs.writeFileSync(fileInfo.path, JSON.stringify({hello: 'world'}));
fs.closeSync(fileInfo.fd);

// Using write stream
const stream = temp.createWriteStream({prefix: 'log-', suffix: '.txt'});
stream.write('Log entry 1\n');
stream.write('Log entry 2\n');
stream.end();

console.log('Stream file created at:', stream.path);

Temporary Directories

Create temporary directories with secure permissions for organizing multiple temporary files.

/**
 * Create a temporary directory asynchronously with secure permissions (0700)
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @param {Function} [callback] - Callback function(err, dirPath)
 * @returns {Promise<string>} Directory path if no callback
 */
temp.mkdir(affixes, callback);

/**
 * Create a temporary directory synchronously with secure permissions (0700)
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @returns {string} Directory path
 */
temp.mkdirSync(affixes);

Usage Examples:

const temp = require('temp');
const fs = require('fs');
const path = require('path');

temp.track();

// Basic temporary directory (async)
temp.mkdir('project-', (err, dirPath) => {
  if (err) throw err;
  
  // Create files within the temporary directory
  const configFile = path.join(dirPath, 'config.json');
  const dataFile = path.join(dirPath, 'data.txt');
  
  fs.writeFileSync(configFile, JSON.stringify({debug: true}));
  fs.writeFileSync(dataFile, 'Application data');
  
  console.log('Project directory created at:', dirPath);
});

// Custom directory settings (sync)
const workDir = temp.mkdirSync({
  prefix: 'build-',
  suffix: '-workspace',
  dir: '/tmp/myapp'
});

console.log('Work directory created at:', workDir);

Path Generation

Generate unique temporary paths without creating files or directories.

/**
 * Generate a unique temporary path without creating the file or directory
 * @param {string|Object} [affixes] - Prefix string or options object {prefix, suffix, dir}
 * @returns {string} Generated temporary path
 */
temp.path(affixes);

Usage Examples:

const temp = require('temp');
const fs = require('fs');

// Generate paths with different configurations
const tempFile = temp.path();
const pdfFile = temp.path({suffix: '.pdf'});
const dataFile = temp.path({prefix: 'data-', suffix: '.json'});
const customPath = temp.path({
  prefix: 'backup-',
  suffix: '.sql',
  dir: '/custom/temp/location'
});

console.log('Generated paths:');
console.log('- Default:', tempFile);
console.log('- PDF:', pdfFile);
console.log('- Data:', dataFile);
console.log('- Custom:', customPath);

// Note: Files are not created automatically
// You must create them yourself and handle cleanup
fs.writeFileSync(pdfFile, 'PDF content here');

// Manual cleanup is required since temp.path() doesn't track files
fs.unlinkSync(pdfFile);

Types

/**
 * File information returned by temp.open() and temp.openSync()
 * @typedef {Object} FileInfo
 * @property {string} path - Full path to the temporary file
 * @property {number} fd - File descriptor for the opened file
 */

/**
 * Cleanup statistics returned by cleanup operations
 * @typedef {Object} CleanupStats
 * @property {number} files - Number of files cleaned up
 * @property {number} dirs - Number of directories cleaned up
 */

/**
 * Affixes configuration for customizing temporary names
 * @typedef {Object} AffixesConfig
 * @property {string} [prefix] - String to prepend to generated name
 * @property {string} [suffix] - String to append to generated name
 * @property {string} [dir] - Custom directory (defaults to system temp)
 */

Error Handling

Common error scenarios and handling patterns:

const temp = require('temp');

// Handle file creation errors
temp.open('myprefix', (err, info) => {
  if (err) {
    if (err.code === 'EACCES') {
      console.error('Permission denied accessing temp directory');
    } else if (err.code === 'ENOSPC') {
      console.error('No space left on device');
    } else {
      console.error('Failed to create temp file:', err.message);
    }
    return;
  }
  
  // Success handling...
});

// Cleanup errors (when not tracking)
temp.cleanup((err, stats) => {
  if (err) {
    if (err.message === 'not tracking') {
      console.error('Cleanup failed: tracking is not enabled');
      console.log('Enable tracking with temp.track()');
    } else {
      console.error('Cleanup error:', err.message);
    }
    return;
  }
  
  console.log('Cleanup successful:', stats);
});

Security Features

  • File Permissions: Files created with 0600 (owner read/write only)
  • Directory Permissions: Directories created with 0700 (owner read/write/execute only)
  • Exclusive Creation: Files created with O_EXCL flag to prevent race conditions
  • Unique Names: Generated using timestamp, process ID, and random components
  • Automatic Cleanup: Optional tracking prevents temporary file accumulation

Default Naming

When no affixes are provided, temp uses these default prefixes:

  • Files (temp.open, temp.openSync): 'f-'
  • Directories (temp.mkdir, temp.mkdirSync): 'd-'
  • Streams (temp.createWriteStream): 's-'

Generated names follow the pattern: {prefix}{year}{month}{day}-{pid}-{random}{suffix}