Skip to content

Instantly share code, notes, and snippets.

@karltaylor
Last active March 24, 2020 11:31
Show Gist options
  • Save karltaylor/88bf67f6699909890b767f895691142a to your computer and use it in GitHub Desktop.
Save karltaylor/88bf67f6699909890b767f895691142a to your computer and use it in GitHub Desktop.
Module to find and replace parts of a file.
const fs = require('fs');
const signale = require('signale');
module.exports = (filePath, regex, replacement) =>
new Promise((yep, nope) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.log(err); // eslint-disable-line
nope(err);
}
if (!data) {
signale.fatal(filePath);
signale.fatal(new Error('File Not Found'));
return;
}
const result = data.replace(new RegExp(regex), replacement);
fs.writeFile(filePath, result, 'utf8', writeError => {
if (writeError) {
console.log(writeError); // eslint-disable-line
nope(writeError);
}
yep('success');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment