Files
replace-in-file/lib/helpers/replace-async.js
Greg Magolan a0045eae5d Pass filename as last arg to replacer function (#34)
* Pass filename as last arg to replacer function

* - Cleaned up replacer function override to use ES6
- Added replacer function tests to Async callback & Sync specs
2017-09-15 09:30:53 +12:00

37 lines
877 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, enc) {
return new Promise((resolve, reject) => {
fs.readFile(file, enc, (error, contents) => {
//istanbul ignore if
if (error) {
return reject(error);
}
//Replace contents and check if anything changed
let newContents = makeReplacements(contents, from, to, file);
if (newContents === contents) {
return resolve({file, hasChanged: false});
}
//Write to file
fs.writeFile(file, newContents, enc, error => {
//istanbul ignore if
if (error) {
return reject(error);
}
resolve({file, hasChanged: true});
});
});
});
};