mirror of
https://github.com/zhigang1992/replace-in-file.git
synced 2026-06-15 02:29:12 +08:00
* Bump dependencies * [feature] #38 Count number of matches * Update make-replacements.js * [feature] #42 Differentiate number of matches and number of replacements * [enhance] #56 Support for CWD parameter * Default config value * [enhance] #63 Add --quiet flag to supress console output in CLI * Update success-handler.js * Update readme and add change log
46 lines
998 B
JavaScript
46 lines
998 B
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Dependencies
|
|
*/
|
|
const fs = require('fs');
|
|
const makeReplacements = require('./make-replacements');
|
|
|
|
/**
|
|
* Helper to replace in a single file (async)
|
|
*/
|
|
module.exports = function replaceAsync(file, from, to, config) {
|
|
|
|
//Extract relevant config
|
|
const {encoding, dry, countMatches} = config;
|
|
|
|
//Wrap in promise
|
|
return new Promise((resolve, reject) => {
|
|
fs.readFile(file, encoding, (error, contents) => {
|
|
//istanbul ignore if
|
|
if (error) {
|
|
return reject(error);
|
|
}
|
|
|
|
//Make replacements
|
|
const [result, newContents] = makeReplacements(
|
|
contents, from, to, file, countMatches
|
|
);
|
|
|
|
//Not changed or dry run?
|
|
if (!result.hasChanged || dry) {
|
|
return resolve(result);
|
|
}
|
|
|
|
//Write to file
|
|
fs.writeFile(file, newContents, encoding, error => {
|
|
//istanbul ignore if
|
|
if (error) {
|
|
return reject(error);
|
|
}
|
|
resolve(result);
|
|
});
|
|
});
|
|
});
|
|
};
|