Replace In File

8.4.0 · active · verified Sun Apr 19

Replace In File is a JavaScript/TypeScript utility for programmatic and CLI-based text replacement within one or more files. Currently at version 8.4.0, it provides both asynchronous (Promise-based) and synchronous APIs, supporting glob patterns for file selection. The library facilitates simple string replacements, complex regular expression substitutions, and handling of multiple replacements with distinct options. Its release cadence includes major version bumps that introduce breaking changes, notably affecting the return value structure. Key differentiators include its flexibility in handling various replacement scenarios, support for custom file system APIs, and a dry-run mode, making it suitable for build scripts, content transformation, and general file manipulation tasks in Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates asynchronous text replacement in a file using a regular expression, including file creation and cleanup.

import { replaceInFile } from 'replace-in-file';
import * as path from 'path';
import * as fs from 'fs';

// Create a dummy file for the example
const dummyFilePath = path.resolve(__dirname, 'temp-example.txt');
fs.writeFileSync(dummyFilePath, 'Hello foo world! Foo bar. This is foo again.');

async function runReplacement() {
  const options = {
    files: dummyFilePath,
    from: /foo/g,
    to: 'bar',
    countMatches: true // Show matches and replacements info
  };

  try {
    console.log(`Initial content of ${path.basename(dummyFilePath)}:`);
    console.log(fs.readFileSync(dummyFilePath, 'utf8'));

    const results = await replaceInFile(options);
    console.log('\nReplacement results:', results);
    // Expected output similar to:
    // [
    //   {
    //     file: '/path/to/temp-example.txt',
    //     hasChanged: true,
    //     numMatches: 3,
    //     numReplacements: 3
    //   }
    // ]

    console.log(`\nContent after replacement in ${path.basename(dummyFilePath)}:`);
    console.log(fs.readFileSync(dummyFilePath, 'utf8')); // Should be "Hello bar world! Bar bar. This is bar again."

  } catch (error) {
    console.error('Error occurred:', error);
  } finally {
    // Clean up the dummy file
    fs.unlinkSync(dummyFilePath);
    console.log(`\nCleaned up ${path.basename(dummyFilePath)}`);
  }
}

runReplacement();

view raw JSON →