Replace In File
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
-
TypeError: replaceInFile is not a function
cause Attempting to use CommonJS `require` syntax or an incorrect named import with a package that is ESM-first or where the symbol is not directly exported as a default.fixEnsure your project is configured for ESM (`"type": "module"` in `package.json` or `.mjs` file extension) and use `import { replaceInFile } from 'replace-in-file';` -
Error: No files found matching 'path/to/non-existent-file.txt'
cause The `files` option specifies a glob pattern or file path that does not match any existing files or is incorrectly formatted.fixVerify the file paths and glob patterns specified in the `files` option. Ensure the target files exist and the pattern correctly resolves to them. -
Error: The "from" option must be a string, RegExp, or array of strings/RegExps.
cause An invalid data type was provided for the `from` option, which expects a string, a regular expression, or an array containing these types.fixCheck the `from` option in your configuration. It must be a `string`, a `RegExp` object, or an `Array` of `string`s or `RegExp`s.
Warnings
- breaking The return value of `replaceInFile` and `replaceInFileSync` changed from an array of changed file paths to a detailed results array, where each object indicates if a file was processed and whether it changed, including match/replacement counts if enabled.
- breaking Support for Node.js versions 4 and 5 was dropped. The package now requires Node.js >=18.
- gotcha When passing a config file path to the CLI, absolute paths now behave as such. Previously, undocumented behavior might have treated them as relative or appended them to the current working directory.
- deprecated The `silent` option was deprecated in favor of `verbose` for clearer control over output. While `silent` might still work, `verbose` offers more explicit control.
Install
-
npm install replace-in-file -
yarn add replace-in-file -
pnpm add replace-in-file
Imports
- replaceInFile
const replaceInFile = require('replace-in-file')import { replaceInFile } from 'replace-in-file' - replaceInFileSync
const { replaceInFileSync } = require('replace-in-file')import { replaceInFileSync } from 'replace-in-file'
Quickstart
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();