Synchronous File Utilities for Node.js CLIs

0.2.2 · maintenance · verified Sun Apr 19

file-utils is a Node.js library offering a set of synchronous file system utilities, derived from Grunt.file. It is primarily designed for command-line interface tools and user utilities, with explicit warnings against its use in Node.js server environments due to its blocking I/O nature. The package enables the creation of scoped file environments (`createEnv`) that automatically prefix paths for file operations, providing isolated contexts for managing files. It also supports "write filters" and "validation filters" which can modify file content/paths or control write actions, respectively. Filters can be asynchronous, which subsequently makes the `write` and `copy` methods asynchronous. The current stable version is 0.2.2, with its latest release focusing on internal cleanup and import performance improvements. Its release cadence is infrequent, and major changes between 0.1.x and 0.2.x primarily involved Node.js version support and the handling of file content types within filters.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a scoped file utility environment, write and read files synchronously, register a write filter to modify content, and clean up resources.

const fs = require('fs');
const path = require('path');
const fileUtils = require('file-utils');

// Ensure a temporary directory exists for testing
const tempDir = path.join(__dirname, 'temp-file-utils-test');
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir);
}

// Create a scoped environment
const env = fileUtils.createEnv({
  base: tempDir,
  dest: path.join(tempDir, 'output') // Optional destination path
});

const filePath = 'my-test-file.txt';
const fileContent = 'Hello, file-utils!\nThis is a synchronous utility example.';

try {
  // Write a file within the scoped base directory
  env.write(filePath, fileContent);
  console.log(`Successfully wrote to ${path.join(tempDir, filePath)}`);

  // Read the file
  const readContent = env.read(filePath);
  console.log(`Successfully read from ${path.join(tempDir, filePath)}`);
  console.log('Content:', readContent);

  // Demonstrate a write filter (e.g., converting content to uppercase)
  env.registerWriteFilter('upper-case', function(file) {
    if (typeof file.contents === 'string') {
      file.contents = file.contents.toUpperCase();
    }
    return file;
  });

  const filteredFilePath = 'my-filtered-file.txt';
  env.write(filteredFilePath, 'This text will be uppercased by a filter.');
  console.log(`Successfully wrote filtered content to ${path.join(tempDir, filteredFilePath)}`);
  console.log('Filtered Content:', env.read(filteredFilePath));

  // Clean up created files and the temporary directory
  env.delete(filePath);
  env.delete(filteredFilePath);
  fs.rmdirSync(tempDir, { recursive: true });
  console.log(`Cleaned up ${tempDir}`);

} catch (error) {
  console.error('An error occurred:', error.message);
  // Ensure cleanup even on error
  if (fs.existsSync(tempDir)) {
    fs.rmdirSync(tempDir, { recursive: true });
  }
}

view raw JSON →