Created
May 11, 2017 16:21
-
-
Save syaau/c9fb034f19475a9ac6614d7e49d59181 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
/** | |
* A JSON formatter that transforms the incoming | |
* stream of JSON data (without proper formatting) | |
* into properly formatted JSON string. | |
* Usage: | |
* yourInputStream.pipe(createJSONFormatter()).pipe(yourOutputStream); | |
*/ | |
const Transform = require('stream').Transform; | |
function createJSONFormatter() { | |
const formatter = Transform(); | |
formatter.jsonData = ''; | |
// Process every chunk and accumulate | |
formatter._transform = function (chunk, enc, cb) { | |
this.jsonData += chunk.toString(); | |
cb(); | |
} | |
// Format the JSON at the end of the stream | |
formatter._flush = function (cb) { | |
const json = JSON.stringify(JSON.parse(this.jsonData), null, 2); | |
this.push(json); | |
cb(); | |
} | |
return formatter; | |
} | |
module.exports = createJSONFormatter; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment