index.js 723 B

12345678910111213141516171819202122232425262728293031
  1. var through = require('through2')
  2. var split = require('split2')
  3. var EOL = require('os').EOL
  4. var stringify = require('json-stringify-safe')
  5. module.exports = parse
  6. module.exports.serialize = module.exports.stringify = serialize
  7. module.exports.parse = parse
  8. function parse (opts) {
  9. opts = opts || {}
  10. opts.strict = opts.strict !== false
  11. function parseRow (row) {
  12. try {
  13. if (row) return JSON.parse(row)
  14. } catch (e) {
  15. if (opts.strict) {
  16. this.emit('error', new Error('Could not parse row ' + row.slice(0, 50) + '...'))
  17. }
  18. }
  19. }
  20. return split(parseRow, opts)
  21. }
  22. function serialize (opts) {
  23. return through.obj(opts, function(obj, enc, cb) {
  24. cb(null, stringify(obj) + EOL)
  25. })
  26. }