Skip to content

Instantly share code, notes, and snippets.

@wbobeirne
Last active September 9, 2016 07:47
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 wbobeirne/63e1b8c3a16ffce6dac5c7d81afd5cec to your computer and use it in GitHub Desktop.
Save wbobeirne/63e1b8c3a16ffce6dac5c7d81afd5cec to your computer and use it in GitHub Desktop.
const fs = require("fs");
module.exports = (args) => {
return (data) => {
let json = null;
// Include the JSON, throw a log and exit if it wasn't JSON / bad path.
try {
json = require(args.path);
if (!json || json.constructor != Object) {
throw new Error(`Alter JSON - Invalid / non-JSON at ${args.path}`);
}
}
catch (err) {
console.log(err.message);
return;
}
// Run their alter function, try to JSONify the results.
const alterResults = args.alter(json, data);
const newJson = JSON.stringify(alterResults, null, args.indentation || 2);
// Save their altered JSON, if it's kosher.
if (newJson) {
try {
fs.writeFileSync(args.path, `${newJson}\r\n`);
return true;
}
catch(err) {
console.log(`Alter JSON - File save error: ${err}`);
return;
}
}
else {
console.log(`Alter JSON - Invalid JSON returned, ${args.path} not saved`);
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment