UNPKG

@naturalcycles/nodejs-lib

Version:
31 lines (30 loc) 1 kB
import { Transform } from 'node:stream'; import { _sortObjectDeep } from '@naturalcycles/js-lib/object'; /** * Transforms objects (objectMode=true) into chunks \n-terminated JSON strings (readableObjectMode=false). */ export function transformToNDJson(opt = {}) { const { strict = true, separator = '\n', sortObjects = false } = opt; return new Transform({ writableObjectMode: true, readableObjectMode: false, readableHighWaterMark: 64 * 1024, transform(chunk, _, cb) { try { if (sortObjects) { chunk = _sortObjectDeep(chunk); } 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 } } }, }); }