LoginSignup
1
1

More than 3 years have passed since last update.

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

Posted at

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

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

import csvParser from "csv-parser"
import { Readable } from "stream"

//CSVが格納された文字列
const csvString = `col1,col2,col3
row1,row2,row3
row1,row2,row3`

// Readable Stream を作成
const readable = new Readable({
    read:(size) => {
        //この処理の記述の必要性が実は良く分からない
        return true
        }
})

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。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1