UNPKG

1.67 kBPlain TextView Raw
1import { Transform } from 'stream'
2import { _sortObjectDeep } from '@naturalcycles/js-lib'
3import { TransformTyped } from '../stream.model'
4
5export interface TransformToNDJsonOptions {
6 /**
7 * If true - will throw an error on JSON.parse / stringify error
8 *
9 * @default true
10 */
11 strict?: boolean
12
13 /**
14 * If true - will run `sortObjectDeep()` on each object to achieve deterministic sort
15 *
16 * @default false
17 */
18 sortObjects?: boolean
19
20 /**
21 * @default `\n`
22 */
23 separator?: string
24
25 /**
26 * @experimental
27 */
28 useFlatstr?: boolean
29}
30
31/**
32 * Transforms objects (objectMode=true) into chunks \n-terminated JSON strings (readableObjectMode=false).
33 */
34export function transformToNDJson<IN = any>(
35 opt: TransformToNDJsonOptions = {},
36): TransformTyped<IN, string> {
37 const { strict = true, separator = '\n', sortObjects = false, useFlatstr = false } = opt
38
39 return new Transform({
40 writableObjectMode: true,
41 readableObjectMode: false,
42 transform(chunk: IN, _, cb) {
43 try {
44 if (sortObjects) {
45 chunk = _sortObjectDeep(chunk as any)
46 }
47
48 if (useFlatstr) {
49 cb(null, flatstr(JSON.stringify(chunk) + separator))
50 } else {
51 cb(null, JSON.stringify(chunk) + separator)
52 }
53 } catch (err) {
54 console.error(err)
55
56 if (strict) {
57 cb(err as Error) // emit error
58 } else {
59 cb() // emit no error, but no result neither
60 }
61 }
62 },
63 })
64}
65
66/**
67 * Based on: https://github.com/davidmarkclements/flatstr/blob/master/index.js
68 */
69function flatstr(s: any): string {
70 // eslint-disable-next-line
71 s | 0
72 return s
73}