{"id":11937,"library":"replace-in-file","title":"Replace In File","description":"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.","status":"active","version":"8.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/adamreisnz/replace-in-file","tags":["javascript","replace","text","contents","file","typescript"],"install":[{"cmd":"npm install replace-in-file","lang":"bash","label":"npm"},{"cmd":"yarn add replace-in-file","lang":"bash","label":"yarn"},{"cmd":"pnpm add replace-in-file","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const replaceInFile = require('replace-in-file')","symbol":"replaceInFile","correct":"import { replaceInFile } from 'replace-in-file'"},{"note":"Similar to `replaceInFile`, prefer ESM imports. CommonJS `require` can be used for older Node.js versions, but modern usage favors `import`.","wrong":"const { replaceInFileSync } = require('replace-in-file')","symbol":"replaceInFileSync","correct":"import { replaceInFileSync } from 'replace-in-file'"}],"quickstart":{"code":"import { replaceInFile } from 'replace-in-file';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\n// Create a dummy file for the example\nconst dummyFilePath = path.resolve(__dirname, 'temp-example.txt');\nfs.writeFileSync(dummyFilePath, 'Hello foo world! Foo bar. This is foo again.');\n\nasync function runReplacement() {\n  const options = {\n    files: dummyFilePath,\n    from: /foo/g,\n    to: 'bar',\n    countMatches: true // Show matches and replacements info\n  };\n\n  try {\n    console.log(`Initial content of ${path.basename(dummyFilePath)}:`);\n    console.log(fs.readFileSync(dummyFilePath, 'utf8'));\n\n    const results = await replaceInFile(options);\n    console.log('\\nReplacement results:', results);\n    // Expected output similar to:\n    // [\n    //   {\n    //     file: '/path/to/temp-example.txt',\n    //     hasChanged: true,\n    //     numMatches: 3,\n    //     numReplacements: 3\n    //   }\n    // ]\n\n    console.log(`\\nContent after replacement in ${path.basename(dummyFilePath)}:`);\n    console.log(fs.readFileSync(dummyFilePath, 'utf8')); // Should be \"Hello bar world! Bar bar. This is bar again.\"\n\n  } catch (error) {\n    console.error('Error occurred:', error);\n  } finally {\n    // Clean up the dummy file\n    fs.unlinkSync(dummyFilePath);\n    console.log(`\\nCleaned up ${path.basename(dummyFilePath)}`);\n  }\n}\n\nrunReplacement();","lang":"typescript","description":"Demonstrates asynchronous text replacement in a file using a regular expression, including file creation and cleanup."},"warnings":[{"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)`.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade your Node.js environment to version 18 or newer to ensure compatibility.","message":"Support for Node.js versions 4 and 5 was dropped. The package now requires Node.js >=18.","severity":"breaking","affected_versions":">=3.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=3.1.0"},{"fix":"Prefer using the `verbose` option (set to `false` for no output) instead of `silent`.","message":"The `silent` option was deprecated in favor of `verbose` for clearer control over output. While `silent` might still work, `verbose` offers more explicit control.","severity":"deprecated","affected_versions":">=7.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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';`","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.","error":"TypeError: replaceInFile is not a function"},{"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.","cause":"The `files` option specifies a glob pattern or file path that does not match any existing files or is incorrectly formatted.","error":"Error: No files found matching 'path/to/non-existent-file.txt'"},{"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.","cause":"An invalid data type was provided for the `from` option, which expects a string, a regular expression, or an array containing these types.","error":"Error: The \"from\" option must be a string, RegExp, or array of strings/RegExps."}],"ecosystem":"npm"}