@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
47 lines (46 loc) • 1.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformToNDJson = void 0;
const stream_1 = require("stream");
const js_lib_1 = require("@naturalcycles/js-lib");
/**
* Transforms objects (objectMode=true) into chunks \n-terminated JSON strings (readableObjectMode=false).
*/
function transformToNDJson(opt = {}) {
const { strict = true, separator = '\n', sortObjects = false, useFlatstr = false } = opt;
return new stream_1.Transform({
writableObjectMode: true,
readableObjectMode: false,
transform(chunk, _, cb) {
try {
if (sortObjects) {
chunk = (0, js_lib_1._sortObjectDeep)(chunk);
}
if (useFlatstr) {
cb(null, flatstr(JSON.stringify(chunk) + separator));
}
else {
cb(null, JSON.stringify(chunk) + separator);
}
}
catch (err) {
console.error(err);
if (strict) {
cb(err); // emit error
}
else {
cb(); // emit no error, but no result neither
}
}
},
});
}
exports.transformToNDJson = transformToNDJson;
/**
* Based on: https://github.com/davidmarkclements/flatstr/blob/master/index.js
*/
function flatstr(s) {
// eslint-disable-next-line
s | 0;
return s;
}