index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. db.collection.find().stream().pipe(Stringify()).pipe(res)
  3. */
  4. var Transform = require('readable-stream/transform')
  5. var stringify = require('json-stringify-safe')
  6. var util = require('util')
  7. util.inherits(Stringify, Transform)
  8. module.exports = Stringify
  9. function Stringify(options) {
  10. if (!(this instanceof Stringify))
  11. return new Stringify(options || {})
  12. if (options && options.replacer) {
  13. this.replacer = options.replacer;
  14. }
  15. if (options && options.space !== undefined) {
  16. this.space = options.space;
  17. }
  18. Transform.call(this, options || {})
  19. this._writableState.objectMode = true
  20. // Array Deliminator and Stringifier defaults
  21. var opener = options && options.opener ? options.opener : '[\n'
  22. var seperator = options && options.seperator ? options.seperator : '\n,\n'
  23. var closer = options && options.closer ? options.closer : '\n]\n'
  24. var stringifier = options && options.stringifier ? options.stringifier : stringify
  25. // Array Deliminators and Stringifier
  26. this.opener = new Buffer(opener, 'utf8')
  27. this.seperator = new Buffer(seperator, 'utf8')
  28. this.closer = new Buffer(closer, 'utf8')
  29. this.stringifier = stringifier
  30. }
  31. // Flags
  32. Stringify.prototype.started = false
  33. // JSON.stringify options
  34. Stringify.prototype.replacer = null
  35. Stringify.prototype.space = 0
  36. Stringify.prototype._transform = function (doc, enc, cb) {
  37. if (this.started) {
  38. this.push(this.seperator)
  39. } else {
  40. this.push(this.opener)
  41. this.started = true
  42. }
  43. doc = this.stringifier(doc, this.replacer, this.space)
  44. this.push(new Buffer(doc, 'utf8'))
  45. cb()
  46. }
  47. Stringify.prototype._flush = function (cb) {
  48. if (!this.started) this.push(this.opener)
  49. this.push(this.closer)
  50. this.push(null)
  51. cb()
  52. }