Node.js Touch Utility

3.1.1 · active · verified Tue Apr 21

The `touch` package for Node.js provides a cross-platform implementation of the Unix `touch(1)` command, enabling programmatic modification of file access and modification times, or the creation of new, empty files. Its current stable version is 3.1.1. The package offers both asynchronous (Promise-based and callback-based) and synchronous APIs, including `touch()`, `touch.sync()`, `touch.ftouch()`, and `touch.ftouchSync()`. A key differentiator is its dual API for file path and file descriptor manipulation, alongside a `nodetouch` CLI executable that mirrors the native `touch` utility. Release cadence is not explicitly stated, but the package maintains a stable API and provides consistent functionality across Node.js versions, focusing on reliable file system interaction.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both asynchronous (Promise-based) and synchronous usage of the `touch` library to create files and update their timestamps, including specific modification times.

import touch from 'touch';
import { promises as fs } from 'fs';

const filename = 'my-file.txt';
const existingFilename = 'existing.txt';

async function runTouchExamples() {
  console.log('--- Async Touch Example ---');
  try {
    // Create a new file or update timestamp if it exists
    await touch(filename, { nocreate: false });
    console.log(`Touched (or created) ${filename}`);

    // Update only modification time of an existing file
    await fs.writeFile(existingFilename, 'Some content.');
    console.log(`Created ${existingFilename} for modification example.`);

    const newModTime = new Date('2023-01-15T10:00:00Z');
    await touch(existingFilename, { mtime: newModTime });
    console.log(`Updated modification time of ${existingFilename} to ${newModTime.toISOString()}`);

  } catch (error) {
    console.error(`Async operation failed: ${error.message}`);
  }

  console.log('\n--- Sync Touch Example ---');
  try {
    const syncFilename = 'sync-file.txt';
    touch.sync(syncFilename, { time: new Date() });
    console.log(`Touched (or created) ${syncFilename} synchronously.`);
  } catch (error) {
    console.error(`Sync operation failed: ${error.message}`);
  }
}

runTouchExamples().finally(async () => {
  // Clean up created files
  try {
    await fs.unlink(filename).catch(() => {});
    await fs.unlink(existingFilename).catch(() => {});
    await fs.unlink('sync-file.txt').catch(() => {});
    console.log('\nCleaned up example files.');
  } catch (err) {
    console.error(`Cleanup failed: ${err.message}`);
  }
});

view raw JSON →