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

const { Transform } = require('stream')

module.exports = function () {
  let last = [0,0,0]
  let found = false
  return new Transform({
    write(buf, enc, next) {
      if (found) {
        this.push(buf)
        return next()
      }
      for (let i = 0; i < buf.length; i++) {
        last[2] = last[1]
        last[1] = last[0]
        last[0] = buf[i]
        if (last[0] === 0x0a && last[1] === 0x0a) {
          found = true
        } else if (last[0] === 0x0a && last[1] === 0x0d && last[2] === 0x0a) {
          found = true
        }
        if (found) {
          this.push(buf.slice(i+1))
          return next()
        }
      }
      next()
    }
  })
}