Last active
September 9, 2016 07:47
-
-
Save wbobeirne/63e1b8c3a16ffce6dac5c7d81afd5cec to your computer and use it in GitHub Desktop.
This file contains 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"); | |
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