Last active
August 11, 2019 19:05
-
-
Save DevComplex/7262b816e68bba4639ab15d8179d0e45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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