Registry / devops / replace-in-file

replace-in-file

JSON →
library8.4.0jsnpmunverified

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.

npm install replace-in-file
INSTALL
IMPORT
SIG · REPLACE-IN-FILE
R
replace-in-file
devopsjavascriptv8.4.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

replaceInFile
import { replaceInFile } from 'replace-in-file'
const replaceInFile = require('replace-in-file')
The package is primarily designed for ESM consumption; ensure your project is configured for ESM (e.g., `type: 'module'` in package.json or using `.mjs` extension). Node.js >=18 is required.
replaceInFileSync
import { replaceInFileSync } from 'replace-in-file'
const { replaceInFileSync } = require('replace-in-file')
Similar to `replaceInFile`, prefer ESM imports. CommonJS `require` can be used for older Node.js versions, but modern usage favors `import`.

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();
replace-in-file --version
Debug
Known issues
breakingThe 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.
fix
Update existing code to process the new results array. To get an array of changed files, use `results.filter(r => r.hasChanged).map(r => r.file)`.
affects: >=4.0.0
breakingSupport for Node.js versions 4 and 5 was dropped. The package now requires Node.js >=18.
fix
Upgrade your Node.js environment to version 18 or newer to ensure compatibility.
affects: >=3.0.0
gotchaWhen 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.
fix
If experiencing issues with CLI config paths, change absolute paths to relative paths by removing any leading slashes, or ensure absolute paths are correctly specified relative to the root.
affects: >=3.1.0
deprecatedThe `silent` option was deprecated in favor of `verbose` for clearer control over output. While `silent` might still work, `verbose` offers more explicit control.
fix
Prefer using the `verbose` option (set to `false` for no output) instead of `silent`.
affects: >=7.0.0
Errors
Common errors & fixes
TypeError: replaceInFile is not a function
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.
fix
Ensure 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'
The `files` option specifies a glob pattern or file path that does not match any existing files or is incorrectly formatted.
fix
Verify 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.
An invalid data type was provided for the `from` option, which expects a string, a regular expression, or an array containing these types.
fix
Check the `from` option in your configuration. It must be a `string`, a `RegExp` object, or an `Array` of `string`s or `RegExp`s.
Upgrade
Version history
8.4.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources
replace-in-file — npm install replace-in-file · libregistry