nthmail / lib / split.js
all-in-one smtp+imap with minimal setup
git clone http://git.nthia.dev/nthmail

module.exports = function (f) {
  let buffer = []
  let bufferLength = 0
  return function write(buf, cb) {
    ;(function next(i) {
      var j = buf.indexOf(0x0a,i)
      if (j < 0) return done(i)
      var line = null
      if (buffer.length > 0) {
        line = Buffer.concat(buffer.concat(buf.slice(i,j)))
        buffer = []
        bufferLength = 0
      } else {
        line = buf.slice(i,j)
      }
      f(line, (err) => {
        if (err) cb(err)
        else next(j+1)
      })
    })(0)
    function done(i) {
      if (i < buf.length-1) {
        buffer.push(buf.slice(i))
        bufferLength += buf.length-i
        if (bufferLength > 8192) {
          return cb(new Error('line too long'))
        }
      }
      cb()
    }
  }
}