mirror of
https://github.com/zhigang1992/replace-in-file.git
synced 2026-06-15 10:37:52 +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
31 lines
726 B
JavaScript
31 lines
726 B
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Dependencies
|
|
*/
|
|
const fs = require('fs');
|
|
const makeReplacements = require('./make-replacements');
|
|
|
|
/**
|
|
* Helper to replace in a single file (sync)
|
|
*/
|
|
module.exports = function replaceSync(file, from, to, config) {
|
|
|
|
//Extract relevant config and read file contents
|
|
const {encoding, dry, countMatches} = config;
|
|
const contents = fs.readFileSync(file, encoding);
|
|
|
|
//Replace contents and check if anything changed
|
|
const [result, newContents] = makeReplacements(
|
|
contents, from, to, file, countMatches
|
|
);
|
|
|
|
//Contents changed and not a dry run? Write to file
|
|
if (result.hasChanged && !dry) {
|
|
fs.writeFileSync(file, newContents, encoding);
|
|
}
|
|
|
|
//Return result
|
|
return result;
|
|
};
|