Explorar o código

Added JSONL parser and stringer.

Eugene Lazutkin %!s(int64=3) %!d(string=hai) anos
pai
achega
51fcdc2c21
Modificáronse 2 ficheiros con 76 adicións e 0 borrados
  1. 21 0
      src/jsonl/parser.js
  2. 55 0
      src/jsonl/stringer.js

+ 21 - 0
src/jsonl/parser.js

@@ -0,0 +1,21 @@
+'use strict';
+
+const gen = require('../gen');
+const asStream = require('../asStream');
+const fixUtf8Stream = require('../utils/fixUtf8Stream');
+const lines = require('../utils/lines');
+
+const parse = reviver => string => JSON.parse(string, reviver);
+
+const parser = options =>
+  asStream(
+    gen(fixUtf8Stream(), lines(), parse(options && options.reviver)),
+    Object.assign({writableObjectMode: false, readableObjectMode: true}, options)
+  );
+
+parser.parse = parse;
+
+module.exports = parser;
+
+// to keep ESM happy
+module.exports.parse = parse;

+ 55 - 0
src/jsonl/stringer.js

@@ -0,0 +1,55 @@
+'use strict';
+
+const {Transform} = require('stream');
+
+const stringify = (replacer, space) => value => JSON.stringify(value, replacer, space);
+
+const stringer = options => {
+  let first = true,
+    prefix = '',
+    suffix = '',
+    separator = '\n',
+    emptyValue,
+    replacer,
+    space;
+  if (options) {
+    if (typeof options.prefix == 'string') prefix = options.prefix;
+    if (typeof options.suffix == 'string') suffix = options.suffix;
+    if (typeof options.separator == 'string') separator = options.separator;
+    if (typeof options.emptyValue == 'string') emptyValue = options.emptyValue;
+    replacer = options.replacer;
+    space = options.space;
+  }
+  return new Transform(
+    Object.assign({writableObjectMode: true}, options, {
+      transform(value, _, callback) {
+        let result = JSON.stringify(value, replacer, space);
+        if (first) {
+          first = false;
+          result = prefix + result;
+        } else {
+          result = separator + result;
+        }
+        this.push(result);
+        callback(null);
+      },
+      flush(callback) {
+        let output;
+        if (first) {
+          output = typeof emptyValue == 'string' ? emptyValue : prefix + suffix;
+        } else {
+          output = suffix;
+        }
+        output && this.push(output);
+        callback(null);
+      }
+    })
+  );
+};
+
+stringer.stringify = stringify;
+
+module.exports = stringer;
+
+// to keep ESM happy
+module.exports.stringify = stringify;