stringer.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const {Transform} = require('stream');
  3. const stringify = (replacer, space) => value => JSON.stringify(value, replacer, space);
  4. const stringer = options => {
  5. let first = true,
  6. prefix = '',
  7. suffix = '',
  8. separator = '\n',
  9. emptyValue,
  10. replacer,
  11. space;
  12. if (options) {
  13. if (typeof options.prefix == 'string') prefix = options.prefix;
  14. if (typeof options.suffix == 'string') suffix = options.suffix;
  15. if (typeof options.separator == 'string') separator = options.separator;
  16. if (typeof options.emptyValue == 'string') emptyValue = options.emptyValue;
  17. replacer = options.replacer;
  18. space = options.space;
  19. }
  20. return new Transform(
  21. Object.assign({writableObjectMode: true}, options, {
  22. transform(value, _, callback) {
  23. let result = JSON.stringify(value, replacer, space);
  24. if (first) {
  25. first = false;
  26. result = prefix + result;
  27. } else {
  28. result = separator + result;
  29. }
  30. this.push(result);
  31. callback(null);
  32. },
  33. flush(callback) {
  34. let output;
  35. if (first) {
  36. output = typeof emptyValue == 'string' ? emptyValue : prefix + suffix;
  37. } else {
  38. output = suffix;
  39. }
  40. output && this.push(output);
  41. callback(null);
  42. }
  43. })
  44. );
  45. };
  46. stringer.stringify = stringify;
  47. module.exports = stringer;
  48. // to keep ESM happy
  49. module.exports.stringify = stringify;