or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

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

index.mddocs/

tmp-promise

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.

Package Information

  • Package Name: tmp-promise
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install tmp-promise

Core Imports

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

ES Modules:

import * as tmpPromise from 'tmp-promise';
// or destructured imports
import { 
  file, fileSync, 
  dir, dirSync, 
  withFile, withDir, 
  tmpName, tmpNameSync, 
  tmpdir, setGracefulCleanup 
} from 'tmp-promise';

Basic Usage

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

// Create a temporary file
const { path, fd, cleanup } = await file();
// work with file here using fd or path
await cleanup();

// Automatic cleanup with disposer pattern
await withFile(async ({ path, fd }) => {
  // work with file here
  // automatic cleanup when function completes or throws
});

// Create a temporary directory
const { path: dirPath, cleanup: dirCleanup } = await dir();
// work with directory here
await dirCleanup();

// Automatic directory cleanup
await withDir(async ({ path }) => {
  // work with directory here
  // automatic cleanup when function completes or throws
});

Capabilities

Temporary File Creation

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

/**
 * Creates a temporary file asynchronously
 * @param options - Optional file creation options from tmp package
 * @returns Promise resolving to FileResult
 */
function file(options?: FileOptions): Promise<FileResult>;

/**
 * Creates a temporary file synchronously (re-exported from tmp)
 * @param options - Optional file creation options from tmp package
 * @returns Synchronous file result with name, fd, removeCallback
 */
function fileSync(options?: FileOptions): SyncFileResult;

/**
 * Disposer pattern for temporary files with automatic cleanup
 * @param fn - Function to execute with the temporary file
 * @param options - Optional file creation options from tmp package
 * @returns Promise resolving to the result of fn
 */
function withFile<T>(
  fn: (result: FileResult) => Promise<T>,
  options?: FileOptions
): Promise<T>;

interface FileResult {
  /** Path to the temporary file */
  path: string;
  /** File descriptor for the temporary file */
  fd: number;
  /** Async cleanup function to remove the file */
  cleanup(): Promise<void>;
}

Temporary Directory Creation

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

/**
 * Creates a temporary directory asynchronously
 * @param options - Optional directory creation options from tmp package
 * @returns Promise resolving to DirectoryResult
 */
function dir(options?: DirOptions): Promise<DirectoryResult>;

/**
 * Creates a temporary directory synchronously (re-exported from tmp)
 * @param options - Optional directory creation options from tmp package
 * @returns Synchronous directory result with name, removeCallback
 */
function dirSync(options?: DirOptions): SyncDirectoryResult;

/**
 * Disposer pattern for temporary directories with automatic cleanup
 * @param fn - Function to execute with the temporary directory
 * @param options - Optional directory creation options from tmp package
 * @returns Promise resolving to the result of fn
 */
function withDir<T>(
  fn: (results: DirectoryResult) => Promise<T>,
  options?: DirOptions
): Promise<T>;

interface DirectoryResult {
  /** Path to the temporary directory */
  path: string;
  /** Async cleanup function to remove the directory */
  cleanup(): Promise<void>;
}

Temporary Name Generation

Generate unique temporary filenames without creating actual files.

/**
 * Generates a unique temporary filename asynchronously
 * @param options - Optional name generation options from tmp package
 * @returns Promise resolving to temporary filename path
 */
function tmpName(options?: TmpNameOptions): Promise<string>;

/**
 * Generates a unique temporary filename synchronously (re-exported from tmp)
 * @param options - Optional name generation options from tmp package
 * @returns Temporary filename path
 */
function tmpNameSync(options?: TmpNameOptions): string;

System Utilities

Utility functions for temporary directory management and cleanup configuration.

/**
 * Returns the system's default temporary directory (re-exported from tmp)
 * @returns Path to system temp directory
 */
function tmpdir(): string;

/**
 * Enables automatic cleanup of temporary files on process exit (re-exported from tmp)
 */
function setGracefulCleanup(): void;

Synchronous Result Types

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

interface SyncFileResult {
  /** Path to the temporary file */
  name: string;
  /** File descriptor for the temporary file */
  fd: number;
  /** Synchronous cleanup function to remove the file */
  removeCallback(): void;
}

interface SyncDirectoryResult {
  /** Path to the temporary directory */
  name: string;
  /** Synchronous cleanup function to remove the directory */
  removeCallback(): void;
}

Options

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:

interface FileOptions {
  /** File mode/permissions (default: 0600) */
  mode?: number;
  /** Filename prefix (default: 'tmp-') */
  prefix?: string;
  /** Filename suffix (default: '.tmp') */
  postfix?: string;
  /** mkstemp-like filename template */
  template?: string;
  /** Directory for temporary file (default: system temp dir) */
  dir?: string;
  /** Number of retry attempts (default: 3) */
  tries?: number;
  /** Keep file on process exit (default: false) */
  keep?: boolean;
  /** Don't return file descriptor (default: false) */
  discardDescriptor?: boolean;
  /** Detach file descriptor from cleanup (default: false) */
  detachDescriptor?: boolean;
}

interface DirOptions {
  /** Directory mode/permissions (default: 0700) */
  mode?: number;
  /** Directory name prefix (default: 'tmp-') */
  prefix?: string;
  /** mkstemp-like directory template */
  template?: string;
  /** Parent directory for temporary dir (default: system temp dir) */
  dir?: string;
  /** Number of retry attempts (default: 3) */
  tries?: number;
  /** Keep directory on process exit (default: false) */
  keep?: boolean;
  /** Recursively remove directory even if not empty (default: false) */
  unsafeCleanup?: boolean;
}

interface TmpNameOptions {
  /** Filename prefix (default: 'tmp-') */
  prefix?: string;
  /** Filename suffix (default: '.tmp') */
  postfix?: string;
  /** mkstemp-like filename template */
  template?: string;
  /** Directory for temporary name (default: system temp dir) */
  dir?: string;
  /** Number of retry attempts (default: 3) */
  tries?: number;
}

Usage Examples

Basic File Operations

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

// Async file creation
const { path, fd, cleanup } = await file({
  prefix: 'myapp-',
  postfix: '.log'
});

// Write to the file
const fs = require('fs');
fs.writeSync(fd, 'Hello, world!');

// Clean up when done
await cleanup();

// Sync file creation
const syncResult = fileSync({ prefix: 'sync-' });
console.log('Sync file:', syncResult.name);
syncResult.removeCallback(); // manual cleanup

Disposer Pattern Examples

import { withFile, withDir } from 'tmp-promise';
import { promises as fs } from 'fs';
import path from 'path';

// File disposer - automatic cleanup
const result = await withFile(async ({ path: filePath, fd }) => {
  // File is automatically cleaned up after this function
  await fs.writeFile(filePath, 'Processing data...');
  const content = await fs.readFile(filePath, 'utf8');
  return content.length;
});

// Directory disposer - automatic cleanup
const fileCount = await withDir(async ({ path: dirPath }) => {
  // Create some files
  await fs.writeFile(path.join(dirPath, 'file1.txt'), 'data1');
  await fs.writeFile(path.join(dirPath, 'file2.txt'), 'data2');
  
  // Count files
  const files = await fs.readdir(dirPath);
  return files.length;
  // Directory is automatically cleaned up here
});

Name Generation

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

// Generate unique filenames without creating files
const filename = await tmpName({
  prefix: 'data-export-',
  postfix: '.csv'
});

const syncFilename = tmpNameSync({
  template: '/tmp/backup-XXXXXX.tar.gz'
});

Error Handling

import { withFile } from 'tmp-promise';

try {
  await withFile(async ({ path, fd }) => {
    // If this throws, cleanup still happens
    throw new Error('Processing failed');
  });
} catch (error) {
  // File has been cleaned up even though function threw
  console.error('Processing failed:', error.message);
}

Graceful Cleanup

import { setGracefulCleanup } from 'tmp-promise';

// Enable automatic cleanup on process exit
setGracefulCleanup();

// Now all temporary files/directories will be cleaned up
// even if the process exits unexpectedly