Sha256: 8f75ac570d31a3b5276364113b3cfc41ce8d6469b1db867d0c549745d4e7e905

Contents?: true

Size: 1.22 KB

Versions: 25

Compression:

Stored size: 1.22 KB

Contents

var Transform = require('stream').Transform

function Parser (options) {
  if (!(this instanceof Parser)) {
    throw new TypeError('Cannot call a class as a function')
  }

  options = options || {}

  Transform.call(this, { objectMode: true })
  this._memory = ''
  this._emitInvalidLines = (options.emitInvalidLines || false)
}

Parser.prototype = Object.create(Transform.prototype)

Parser.prototype._handleLines = function (lines, cb) {
  for (var i = 0; i < lines.length; i++) {
    if (lines[i] === '') continue

    var err = null
    var json = null
    try {
      json = JSON.parse(lines[i])
    } catch (_err) {
      _err.source = lines[i]
      err = _err
    }

    if (err) {
      if (this._emitInvalidLines) {
        this.emit('invalid-line', err)
      } else {
        return cb(err)
      }
    } else {
      this.push(json)
    }
  }

  cb(null)
}

Parser.prototype._transform = function (chunk, encoding, cb) {
  var lines = (this._memory + chunk.toString()).split('\n')

  this._memory = lines.pop()
  this._handleLines(lines, cb)
}

Parser.prototype._flush = function (cb) {
  if (!this._memory) return cb(null)

  var line = this._memory

  this._memory = ''
  this._handleLines([ line ], cb)
}

module.exports = Parser

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
immosquare-cleaner-0.1.52 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.51 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.50 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.49 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.48 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.47 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.46 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.45 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.44 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.43 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.42 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.41 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.40 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.39 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.38 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.32 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.31 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.30 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.29 node_modules/jsonlines/lib/parser.js
immosquare-cleaner-0.1.28 node_modules/jsonlines/lib/parser.js