LoginSignup
0
0

More than 3 years have passed since last update.

【Node.js csvファイルを一行ずつストリーミング】

Posted at

Streamの使い方を試すためにcsvファイルを一行ずつストリーミングして表示するものを作ってみることにした。

今回はconsoleに表示するだけなので、読み込みstreamだけ使う。

readlineモジュールと読み込みStreamを組み合わせる。

const fs = require('fs');
const readline = require('readline');

//index.csvは50行あることにする
var fileName = 'index.csv';

const rs = fs.createReadStream(fileName, {encoding: "utf8"});
const rl = readline.createInterface({ input: rs });

let count = 0;
rl.on('line', (army) => {
    count++;
    console.log(army + '\n');
  });
rl.on('close', () => {
    console.log(count); // index.csvは50行なので50が表示される
});

外部ファイルに書き込みたい場合は書き込みstreamも組み合わせる。

以下の記事を参考にさせていただきました。

https://qiita.com/tarotaro1129/items/93521afd693796eb2cfa

0
0
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
0
0