UNPKG

1.48 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.transformToNDJson = void 0;
4const stream_1 = require("stream");
5const js_lib_1 = require("@naturalcycles/js-lib");
6/**
7 * Transforms objects (objectMode=true) into chunks \n-terminated JSON strings (readableObjectMode=false).
8 */
9function transformToNDJson(opt = {}) {
10 const { strict = true, separator = '\n', sortObjects = false, useFlatstr = false } = opt;
11 return new stream_1.Transform({
12 writableObjectMode: true,
13 readableObjectMode: false,
14 transform(chunk, _, cb) {
15 try {
16 if (sortObjects) {
17 chunk = (0, js_lib_1._sortObjectDeep)(chunk);
18 }
19 if (useFlatstr) {
20 cb(null, flatstr(JSON.stringify(chunk) + separator));
21 }
22 else {
23 cb(null, JSON.stringify(chunk) + separator);
24 }
25 }
26 catch (err) {
27 console.error(err);
28 if (strict) {
29 cb(err); // emit error
30 }
31 else {
32 cb(); // emit no error, but no result neither
33 }
34 }
35 },
36 });
37}
38exports.transformToNDJson = transformToNDJson;
39/**
40 * Based on: https://github.com/davidmarkclements/flatstr/blob/master/index.js
41 */
42function flatstr(s) {
43 // eslint-disable-next-line
44 s | 0;
45 return s;
46}