node.js csvモジュールをインストールしてcsvファイルを読み込む

node.js csvモジュールをインストールしてcsvファイルを読み込む

node.js で、モジュールcsvのparseを使用して、csvファイルを読み込むサンプルコードを記述してます。nodeのバージョンは、14.15.1です。

環境

  • OS  CentOS Stream release 8
  • node V14.15.1
  • npm 6.14.7

csvモジュールインストール

npmでインストールしておきます。

npm i csv

csv読み込み

parseを使用して、後でpipeに指定することでcsvファイルを読み込むことが可能です。

sample.csv(カンマの後に空白を入れてます)

ソースコード

const csv = require('csv');
const fs = require('fs');
const path = require('path');

// trim:trueにするとカンマの前後のスペースが削除されます
const parser = csv.parse({ trim: true },
    (e, result) => (e) ? console.error(e) : console.log(result)
);

// 読み込みとparserの処理を実行
fs.createReadStream('sample.csv').pipe(parser);

実行結果

[ [ 'a', 'b', 'c' ], [ '1', '2', '3' ], [ '4', '5', '6' ] ]

「columns: true」とすれば、1行目をヘッダーとして扱うことが可能です。

const parser = csv.parse({ columns: true, trim: true },
    (e, result) => (e) ? console.error(e) : console.log(result)
);

実行結果

[ { a: '1', b: '2', c: '3' }, { a: '4', b: '5', c: '6' } ]

以下のようにカラム名を指定することも可能です。

const parser = csv.parse({ columns: ['d', 'e', 'f'], trim: true },
    (e, result) => (e) ? console.error(e) : console.log(result)
);

実行結果

[
  { d: 'a', e: 'b', f: 'c' },
  { d: '1', e: '2', f: '3' },
  { d: '4', e: '5', f: '6' }
]