Skip to content

Instantly share code, notes, and snippets.

@DevComplex
Last active August 11, 2019 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevComplex/7262b816e68bba4639ab15d8179d0e45 to your computer and use it in GitHub Desktop.
Save DevComplex/7262b816e68bba4639ab15d8179d0e45 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const args = process.argv.slice(2);
if (args.length > 1) {
console.error("Invalid number of arguments. Please only pass one!");
}
const fileName = args[0];
if (!fileName) {
console.error("Invalid file name passed!");
}
const FILE_PATH = __dirname + "/" + fileName;
function readFromFile() {
return new Promise(resolve => {
fs.readFile(FILE_PATH, "utf8", (err, data) => {
if (err) {
console.error(`Error reading file: ${FILE_PATH}`, err);
} else if (data) {
resolve(data);
}
});
});
}
function modifyFileContents(fileContents) {
return fileContents
.split("")
.reduce((acc, next) => {
if (next === '"') {
acc.push("\\");
}
acc.push(next);
return acc;
}, [])
.join("");
}
function writeToFile(contents) {
return new Promise(resolve => {
fs.writeFile(FILE_PATH, contents, err => {
if (err) {
console.error(`Error writing to file: ${FILE_PATH}`, err);
} else {
resolve();
}
});
});
}
readFromFile()
.then(fileContents => modifyFileContents(fileContents))
.then(modifiedFileContents => writeToFile(modifiedFileContents));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment