| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- '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;
|