@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
41 lines • 1.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
/**
* Transforms chunks of JSON strings/Buffers (objectMode=false) into parsed objects (readableObjectMode=true).
*
* if strict - will throw an error on JSON.parse / stringify error
*
* Usage:
*
* await _pipeline([
* readable,
* binarySplit(),
* transformJsonParse(),
* consumeYourStream...
* [)
*/
function transformJsonParse(opt = {}) {
const { strict = true } = opt;
return new stream_1.Transform({
objectMode: false,
readableObjectMode: true,
transform(chunk, _encoding, cb) {
try {
const data = JSON.parse(chunk);
cb(null, data);
}
catch (err) {
// console.error(err)
if (strict) {
cb(err); // emit error
}
else {
cb(); // emit no error, but no result neither
}
}
},
});
}
exports.transformJsonParse = transformJsonParse;
//# sourceMappingURL=transformJsonParse.js.map