
/*

  db.collection.find().stream().pipe(Stringify()).pipe(res)

*/

var Transform = require('readable-stream/transform')
var stringify = require('json-stringify-safe')
var util = require('util')

util.inherits(Stringify, Transform)

module.exports = Stringify

function Stringify(options) {
  if (!(this instanceof Stringify))
    return new Stringify(options || {})

  Transform.call(this, options || {})
  this._writableState.objectMode = true
}

// Flags
Stringify.prototype.destroyed = false
Stringify.prototype.started = false

// Array delimiters
Stringify.prototype.open = new Buffer('[\n', 'utf8')
Stringify.prototype.seperator = new Buffer('\n,\n', 'utf8')
Stringify.prototype.close = new Buffer('\n]\n', 'utf8')

// JSON.stringify options
Stringify.prototype.replacer = null
Stringify.prototype.space = 0

Stringify.prototype._transform = function (doc, enc, cb) {
  if (this.destroyed)
    return

  if (this.started) {
    this.push(this.seperator)
  } else {
    this.push(this.open)
    this.started = true
  }

  try {
    doc = stringify(doc, this.replacer, this.space)
  } catch (err) {
    cb(err)
    return
  }

  this.push(new Buffer(doc, 'utf8'))
  cb()
}

Stringify.prototype._flush = function (cb) {
  if (this.destroyed)
    return

  if (!this.started)
    this.push(this.open)

  this.push(this.close)
  this.push(null)
  cb()
}

Stringify.prototype.destroy = function () {
  if (!this.destroyed) {
    this.emit('close')
    this.destroyed = true
  }
}

@@ -457,46 +457,8 @@
 ags%0A
-Stringify.prototype.destroyed = false%0A
 Stri
@@ -836,42 +836,8 @@
 ) %7B%0A
-  if (this.destroyed)%0A    return%0A%0A
   if
@@ -953,18 +953,8 @@
  %7D%0A%0A
-  try %7B%0A  
   do
@@ -1002,53 +1002,8 @@
 ace)
-%0A  %7D catch (err) %7B%0A    cb(err)%0A    return%0A  %7D
 %0A%0A  
@@ -1096,42 +1096,8 @@
 ) %7B%0A
-  if (this.destroyed)%0A    return%0A%0A
   if
@@ -1112,20 +1112,16 @@
 started)
-%0A   
  this.pu
@@ -1134,17 +1134,16 @@
 s.open)%0A
-%0A
   this.p
@@ -1189,129 +1189,4 @@
 )%0A%7D%0A
-%0AStringify.prototype.destroy = function () %7B%0A  if (!this.destroyed) %7B%0A    this.emit('close')%0A    this.destroyed = true%0A  %7D%0A%7D%0A

remove unnecessary .destroy()