example.js 874 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var peek = require('peek-stream')
  2. var ldjson = require('ldjson-stream')
  3. var csv = require('csv-parser')
  4. var isCSV = function(data) {
  5. return data.toString().indexOf(',') > -1
  6. }
  7. var isJSON = function(data) {
  8. try {
  9. JSON.parse(data)
  10. return true
  11. } catch (err) {
  12. return false
  13. }
  14. }
  15. var parser = function() {
  16. return peek(function(data, swap) {
  17. // maybe it is JSON?
  18. if (isJSON(data)) return swap(null, ldjson())
  19. // maybe it is CSV?
  20. if (isCSV(data)) return swap(null, csv())
  21. // we do not know - bail
  22. swap(new Error('No parser available'))
  23. })
  24. }
  25. var parse = parser()
  26. parse.write('{"hello":"world"}\n{"hello":"another"}\n')
  27. parse.on('data', function(data) {
  28. console.log('from ldj:', data)
  29. })
  30. var parse = parser()
  31. parse.write('test,header\nvalue-1,value-2\n')
  32. parse.on('data', function(data) {
  33. console.log('from csv:', data)
  34. })