Adam Reis 849c1b653a 2.4.0
2017-02-21 21:26:40 +13:00
2017-02-21 21:26:01 +13:00
2017-02-13 18:29:46 +13:00
2016-02-16 15:34:21 +13:00
2016-02-16 15:20:46 +13:00
2016-12-19 07:47:22 +13:00
2016-06-02 16:28:34 +12:00
2017-02-21 21:26:40 +13:00
2017-02-21 21:26:01 +13:00
2017-02-13 18:29:46 +13:00

Replace in file

npm version node dependencies build status coverage status github issues

A simple utility to quickly replace text in one or more files or globs. Works synchronously or asynchronously with either promises or callbacks. Make a single replacement or multiple replacements at once.

Installation

npm install replace-in-file

Usage

Specify options:

const replace = require('replace-in-file');
const options = {

  //Single file
  files: 'path/to/file',

  //Multiple files
  files: [
    'path/to/file',
    'path/to/other/file',
  ],

  //Glob(s)
  files: [
    'path/to/files/*.html',
    'another/**/*.path',
  ],

  //Replacement to make (string or regex)
  from: /foo/g,
  to: 'bar',

  //Multiple replacements with the same string (replaced sequentially)
  from: [/foo/g, /baz/g],
  to: 'bar',

  //Multiple replacements with different strings (replaced sequentially)
  from: [/foo/g, /baz/g],
  to: ['bar', 'bax'],

  //Specify if empty/invalid file paths are allowed (defaults to false)
  //If set to true these paths will fail silently and no error will be thrown.
  allowEmptyPaths: false,

  //Character encoding for reading/writing files (defaults to utf-8)
  encoding: 'utf8',
};

Asynchronous replacement, with promises:

replace(options)
  .then(changedFiles => {
    console.log('Modified files:', changedFiles.join(', '));
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Asynchronous replacement, with callback:

replace(options, (error, changedFiles) => {
  if (error) {
    return console.error('Error occurred:', error);
  }
  console.log('Modified files:', changedFiles.join(', '));
});

Synchronous replacement:

try {
  let changedFiles = replace.sync(options);
  console.log('Modified files:', changedFiles.join(', '));
}
catch (error) {
  console.error('Error occurred:', error);
}

Via CLI:

replace-in-file from to some/file.js,some/**/glob.js [--isRegex]

The flags allowEmptyPaths and encoding are supported in the CLI. In addition, the CLI supports the verbose flag to list the changed files.

Multiple files or globs can be replaced by providing a comma separated list.

A regular expression may be used for the from parameter by specifying the --isRegex flag.

License

(MIT License)

Copyright 2015-2017, Adam Reis

Description
No description provided
Readme 372 KiB
Languages
JavaScript 100%