Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8837

csv-parser モジュールでCSV文字列を処理したい場合の方法

$
0
0

csv-parser で CSV文字列をパースする。

https://www.npmjs.com/package/csv-parser

上のモジュールで単純なCSV文字列をパースしたい場合はリーダブルストリームを
一旦生成することで csv-parserのインターフェイスを合わせる事ができる。
(もっと簡単な方法がありそう

importcsvParserfrom"csv-parser"import{Readable}from"stream"//CSVが格納された文字列constcsvString=`col1,col2,col3
row1,row2,row3
row1,row2,row3`// Readable Stream を作成constreadable=newReadable({read:(size)=>{//この処理の記述の必要性が実は良く分からないreturntrue}})readable.on("data",(chunk)=>{//parse されたデータconsole.log(chunk)}).on("err",(err)=>{//error 時の処理}).on("end",()=>{//終了時の処理}).write(csvString,(err)=>{//CSV文字列をストリームに書き込む//close イベントを emit するreadable.emit("end")})

Promiseが必要であれば end コールバックでResolveすれば多分OK。


Viewing all articles
Browse latest Browse all 8837

Trending Articles