Last active
April 19, 2021 20:38
-
-
Save MarkBennett/b6efd8df7c6c57a7035c63c3ba75aa6c to your computer and use it in GitHub Desktop.
Output JSON from STDIN Line-By-Line And Pretty Print
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
/* | |
* Credit to the Node.js Docs for the line-by-line `ReadStream` example. | |
* | |
* https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line | |
*/ | |
const readline = require('readline'); | |
var stdin = process.stdin; | |
stdin.resume(); | |
stdin.setEncoding('utf8'); | |
/** | |
* Handy function for formatting messages that return JSON in their body. | |
* | |
* Comment out the full logging if you need this instead. | |
*/ | |
function formatMessage(message) { | |
console.log(`url = ${message.url}`); | |
if (message.responseBody) { | |
console.log(`response body = \n\n${JSON.stringify(JSON.parse(message.responseBody), null, 2)}`); | |
} | |
} | |
async function processLineByLine() { | |
const rl = readline.createInterface({ | |
input: stdin, | |
crlfDelay: Infinity | |
}); | |
// Note: we use the crlfDelay option to recognize all instances of CR LF | |
// ('\r\n') in input.txt as a single line break. | |
for await (const line of rl) { | |
// Each line in input.txt will be successively available here as `line`. | |
const message = JSON.parse(line); | |
console.log("\n\n==================\n"); | |
console.log(JSON.stringify(message, null, 2)); | |
//formatMessage(message); | |
} | |
} | |
processLineByLine(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment