CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tmp

Temporary file and directory creator for Node.js applications

Pending
Overview
Eval results
Files

name-generation.mddocs/

Name Generation

Generate unique temporary filenames without creating actual filesystem objects, useful for custom file creation workflows and when you need control over the file creation process.

Capabilities

Asynchronous Name Generation

Generates a unique temporary filename asynchronously without creating the file.

/**
 * Generates a unique temporary filename
 * @param {Options|Function} options - Configuration options or callback function
 * @param {Function} callback - Callback function (err, name) => void  
 */
function tmpName(options, callback);

Callback Parameters:

  • err (Error|null): Error object or null if successful
  • name (string): Generated unique temporary filename path

Usage Examples:

const tmp = require("tmp");

// Basic name generation
tmp.tmpName(function(err, path) {
  if (err) throw err;
  
  console.log("Generated temp filename:", path);
  // Example: /tmp/tmp-12345-67890abcdef
  
  // Now you can create the file yourself with custom logic
  const fs = require("fs");
  const fd = fs.openSync(path, "w", 0o600);
  fs.writeSync(fd, "Custom file creation");
  fs.closeSync(fd);
  
  // Clean up manually
  fs.unlinkSync(path);  
});

// Name generation with custom options
tmp.tmpName({ 
  prefix: "myapp-",
  postfix: ".json",
  dir: "data"
}, function(err, path) {
  if (err) throw err;
  
  console.log("Custom temp filename:", path);
  // Example: /tmp/data/myapp-12345-67890abcdef.json
  
  // Create JSON file with specific formatting
  const fs = require("fs");
  const data = { id: Date.now(), type: "temporary" };
  fs.writeFileSync(path, JSON.stringify(data, null, 2));
  
  // Process the file...
  
  fs.unlinkSync(path);
});

// Template-based name generation
tmp.tmpName({ template: "cache-XXXXXX.tmp" }, function(err, path) {
  if (err) throw err;
  
  console.log("Template filename:", path);
  // Example: /tmp/cache-abc123.tmp
  
  // Create cache file with atomic write
  const fs = require("fs");
  const tempPath = path + ".writing";
  fs.writeFileSync(tempPath, "cache data");
  fs.renameSync(tempPath, path); // Atomic operation
  
  fs.unlinkSync(path);
});

Synchronous Name Generation

Generates a unique temporary filename synchronously.

/**
 * Generates a unique temporary filename synchronously
 * @param {Options} options - Configuration options
 * @returns {string} Generated unique temporary filename path
 * @throws {Error} If name generation fails after max tries
 */
function tmpNameSync(options);

Usage Examples:

const tmp = require("tmp");
const fs = require("fs");

// Basic synchronous name generation
const tempName = tmp.tmpNameSync();
console.log("Generated temp filename:", tempName);

// Create and use the file
fs.writeFileSync(tempName, "Synchronous content");
console.log("File content:", fs.readFileSync(tempName, "utf8"));
fs.unlinkSync(tempName);

// Name generation with specific requirements
const configName = tmp.tmpNameSync({
  prefix: "config-",
  postfix: ".yaml",
  mode: 0o644,
  dir: "configs"  
});

console.log("Config filename:", configName);

// Create configuration file
const config = `
app:
  name: MyApp
  debug: true
`;
fs.writeFileSync(configName, config.trim());

// Use the config file...

fs.unlinkSync(configName);

// Generate multiple unique names
const names = [];
for (let i = 0; i < 5; i++) {
  names.push(tmp.tmpNameSync({ prefix: `batch-${i}-` }));
}

console.log("Generated batch names:", names);

// Create all files
names.forEach((name, index) => {
  fs.writeFileSync(name, `Batch file ${index}`);
});

// Clean up
names.forEach(name => fs.unlinkSync(name));

Advanced Name Generation Patterns

Custom Directory Structure

const tmp = require("tmp");
const fs = require("fs");
const path = require("path");

// Generate name in nested directory structure
tmp.tmpName({ 
  dir: "project/build/artifacts",
  prefix: "artifact-",
  postfix: ".tar.gz"
}, function(err, artifactPath) {
  if (err) throw err;
  
  // Ensure parent directories exist
  fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
  
  // Create artifact file
  fs.writeFileSync(artifactPath, "artifact data");
  
  console.log("Artifact created:", artifactPath);
  
  // Clean up
  fs.unlinkSync(artifactPath);
});

Template Patterns for Specific Use Cases

// Log file with timestamp pattern
const logName = tmp.tmpNameSync({ 
  template: "app-log-XXXXXX.log",
  dir: "logs"
});

// Database backup pattern  
const backupName = tmp.tmpNameSync({
  template: "db-backup-XXXXXX.sql",
  tmpdir: "/var/backups"
});

// Session file pattern
const sessionName = tmp.tmpNameSync({
  template: "session-XXXXXX.json", 
  dir: "sessions",
  mode: 0o600  // Secure permissions
});

Retry Logic and Error Handling

const tmp = require("tmp");

// Handle name generation with custom retry logic
function generateNameWithRetry(options, maxAttempts = 5) {
  return new Promise((resolve, reject) => {
    let attempts = 0;
    
    function tryGenerate() {
      attempts++;
      tmp.tmpName(options, function(err, name) {
        if (err) {
          if (attempts < maxAttempts) {
            console.log(`Attempt ${attempts} failed, retrying...`);
            setTimeout(tryGenerate, 100); // Wait before retry
          } else {
            reject(new Error(`Failed to generate name after ${maxAttempts} attempts`));
          }
        } else {
          resolve(name);
        }
      });
    }
    
    tryGenerate();
  });
}

// Usage
generateNameWithRetry({ prefix: "critical-", postfix: ".data" })
  .then(name => {
    console.log("Generated with retry:", name);
    // Use the name...
  })
  .catch(err => {
    console.error("Name generation failed:", err.message);
  });

Name Generation Options

Name generation supports all the standard options:

interface NameGenerationOptions {
  prefix?: string;             // Filename prefix (default: "tmp")
  postfix?: string;            // Filename postfix  
  template?: string;           // Template with XXXXXX (e.g., "temp-XXXXXX.txt")
  name?: string;               // Fixed filename (relative to dir/tmpdir)
  dir?: string;                // Subdirectory within tmpdir
  tmpdir?: string;             // Override system temp directory
  tries?: number;              // Max naming attempts (default: 3)
}

Important Notes:

  • Name generation only creates the filename - you must create the actual file yourself
  • The generated path is guaranteed to not exist at the time of generation, but this can change before you create the file
  • Use atomic file operations (write to temp name, then rename) for thread-safe file creation
  • Template patterns must contain exactly one XXXXXX sequence
  • The tries option controls how many attempts are made if the generated name already exists
  • Name generation is faster than file/directory creation since no filesystem operations are performed
  • Generated names use the same crypto-based randomness as file and directory creation for security

Install with Tessl CLI

npx tessl i tessl/npm-tmp

docs

cleanup-management.md

directory-operations.md

file-operations.md

index.md

name-generation.md

tile.json