npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

replace-in-files

v3.0.0

Published

Replace text in one or more files or globs. Works asynchronously with promises.

Downloads

44,103

Readme

replace-in-files

Replace text in one or more files or globs. Works asynchronously with promises.

npm version dependencies Status Build Status Coverage Status

Installation

# Using npm
npm install replace-in-files

# Using yarn
yarn add replace-in-files

Usage

Specify options

const replaceInFiles = require('replace-in-files');

const options = {
  // See more: https://www.npmjs.com/package/globby
  // Single file or glob
  files: 'path/to/file',
  // Multiple files or globs
  files: [
    'path/to/file',
    'path/to/other/file',
    'path/to/files/*.html',
    'another/**/*.path',
  ],


  // See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
  // Replacement
  from: /foo/g,  // string or regex
  to: 'bar', // string or fn  (fn: carrying last argument - path to replaced file)


  // See more: https://www.npmjs.com/package/glob
  optionsForFiles: { // default
    "ignore": [
      "**/node_modules/**"
    ]
  }


  // format: `${fileName}-${year}-${month}-${day}_${hour}:${minute}:${second}.{fileExtension}`
  //            fileName-2017-11-01_21:29:55.js
  // date of createFile old file or last modificate (if not find create date)
  saveOldFile: false // default


  //Character encoding for reading/writing files
  encoding: 'utf8',  // default


  shouldSkipBinaryFiles: true, // default
  onlyFindPathsWithoutReplace: false // default
  returnPaths: true // default
  returnCountOfMatchesByPaths: true // default
};

Replacing multiple occurrences

Please note that the value specified in the from parameter is passed straight to the native String replace method. As such, if you pass a string as the from parameter, it will only replace the first occurrence.

To replace multiple occurrences at once, you must use a regular expression for the from parameter with the global flag enabled, e.g. /foo/g.

Asynchronous replacement with promises

const replaceInFiles = require('replace-in-files');

// ...

replaceInFiles(options)
  .then(({ changedFiles, countOfMatchesByPaths }) => {
    console.log('Modified files:', changedFiles);
    console.log('Count of matches by paths:', countOfMatchesByPaths);
    console.log('was called with:', options);
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Asynchronous replacement with co yield

const replaceInFiles = require('replace-in-files');
const co = require('co');

// ...

co(function* () {
  const {
    changedFiles,
    countOfMatchesByPaths,
    replaceInFilesOptions
  } = yield replaceInFiles(options);
  console.log('Modified files:', changedFiles);
  console.log('Count of matches by paths:', countOfMatchesByPaths);
  console.log('was called with:', replaceInFilesOptions);
}).catch((error) => {
  console.log('Error occurred:', error);
});

Asynchronous replacement with async await (node 8+)

const replaceInFiles = require('replace-in-files');

// ...

async function main() {
  try {
    const {
      changedFiles,
      countOfMatchesByPaths,
      replaceInFilesOptions
    } = await replaceInFiles(options);
    console.log('Modified files:', changedFiles);
    console.log('Count of matches by paths:', countOfMatchesByPaths);
    console.log('was called with:', replaceInFilesOptions);
  } catch (error) {
    console.log('Error occurred:', error);
  }
}

main();

Sequentially replacement

use .pipe - will be replaced with only files found at first replacement

.pipe supported only: { from, to } (the other options will be received from options in the first replacement)

const replaceInFiles = require('replace-in-files');

// ...

async function main() {
  try {
    const {
      changedFiles,
      countOfMatchesByPaths,
      replaceInFilesOptions
    } = await replaceInFiles(options)
      .pipe({ from: 'foo', to: 'bar' })
      .pipe({ from: 'first', to: 'second' })
      .pipe({ from: /const/g, to: () => 'var' });
    console.log('Modified files:', changedFiles);
    console.log('Count of matches by paths:', countOfMatchesByPaths);
    console.log('was called with:', replaceInFilesOptions);
  } catch (error) {
    console.log('Error occurred:', error);
  }
}

main();

Return value

The return value of the library is an object with: countOfMatchesByPaths and paths

For example:

const replaceInFiles = require('replace-in-files');

const data = replaceInFiles({
  files: 'path/to/files/*.html',
  from: 'a',
  to: 'b',
});

// data could like:
{
  countOfMatchesByPaths: [
    {
      'path/to/files/file1.html': 5,
      'path/to/files/file3.html': 1,
      'path/to/files/file5.html': 3
    }
  ],
  paths: [
    'path/to/files/file1.html',
    'path/to/files/file3.html',
    'path/to/files/file5.html',
  ],
  replaceInFilesOptions: [
    {
      files: 'path/to/files/*.html',
      from: 'a',
      to: 'b',
    }
  ]
}

// if empty:
{
  countOfMatchesByPaths: [
    {}
  ],
  paths: []
}

// if used 2 .pipe
{
  countOfMatchesByPaths: [
    {
      'path/to/files/file1.html': 5,
      'path/to/files/file3.html': 1,
      'path/to/files/file5.html': 3
    },
    {
      'path/to/files/file5.html': 4
    },
    {
      'path/to/files/file1.html': 2,
      'path/to/files/file5.html': 4
    }
  ],
  paths: [
    'path/to/files/file1.html',
    'path/to/files/file3.html',
    'path/to/files/file5.html',
  ],
  replaceInFilesOptions: [
    {
      files: 'path/to/files/*.html',
      from: 'a',
      to: 'b',
    },
    {
      from: 'c',
      to: 'd',
    },
    {
      from: 'e',
      to: 'f',
    }
  ]
}

Version information

Replace in files requires Node 12 or higher. (v.3.0.0 +) potentially still supported earlier node, but in pipeline eslint required node >=12 Replace in files requires Node 8 or higher. (v.2.0.3) - potentially still supported node 6, but in pipeline eslint required node 8 Replace in files requires Node 6 or higher. (v.1.1.4)

License

(MIT License)