Skip to content

Instantly share code, notes, and snippets.

@skovalyov
Created September 18, 2012 12:25
Show Gist options
  • Save skovalyov/3742840 to your computer and use it in GitHub Desktop.
Save skovalyov/3742840 to your computer and use it in GitHub Desktop.
JSON format command line utility
fs = require "fs"
inFile = process.argv[2] # Read the input file name from the 1st command line parameter.
outFile = process.argv[3] # Read the output file name from the 2nd optional command line parameter.
fs.readFile inFile, "utf8", (err, data) -> # Read the input file content.
if err
console.log err # Log error to console.
else
try
object = JSON.parse data # Parse the input file content as JSON.
result = JSON.stringify object, null, " " # Serialize the object to JSON again using double space indentation.
catch e
result = "Invalid JSON" # Show the error message if JSON parsing fails.
if outFile
fs.writeFile outFile, result # If ouput file name is defined, write the result to it.
else
console.log result # Otherwise write the result to console.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment