You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Transform stream that lets you peek the first line before deciding how to parse it
npm install peek-stream
Usage
varpeek=require('peek-stream')varldjson=require('ldjson-stream')varcsv=require('csv-parser')varisCSV=function(data){returndata.toString().indexOf(',')>-1}varisJSON=function(data){try{JSON.parse(data)returntrue}catch(err){returnfalse}}// call parser to create a new parservarparser=function(){returnpeek(function(data,swap){// maybe it is JSON?if(isJSON(data))returnswap(null,ldjson())// maybe it is CSV?if(isCSV(data))returnswap(null,csv())// we do not know - bailswap(newError('No parser available'))})}
The above parser will be able to parse both line delimited JSON and CSV
varparse=parser()parse.write('{"hello":"world"}\n{"hello":"another"}\n')parse.on('data',function(data){console.log(data)// prints {hello:'world'} and {hello:'another'}})
Or
varparse=parser()parse.write('test,header\nvalue-1,value-2\n')parse.on('data',function(data){console.log(data)// prints {test:'value-1', header:'value-2'}})
Per default data is the first line (or the first 65535 bytes if no newline is found).
To change the max buffer pass an options map to the constructor