Skip to content

Instantly share code, notes, and snippets.

@syaau
Created May 11, 2017 16:21
Show Gist options
  • Save syaau/c9fb034f19475a9ac6614d7e49d59181 to your computer and use it in GitHub Desktop.
Save syaau/c9fb034f19475a9ac6614d7e49d59181 to your computer and use it in GitHub Desktop.
/**
* 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