Created
September 18, 2012 12:25
-
-
Save skovalyov/3742840 to your computer and use it in GitHub Desktop.
JSON format command line utility
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
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