JavaScript

Node.js CSV まとめ

CSV読み込み

$ npm install csv
sample.csv
fruit
apple
#banana
orange
lemon
function readCsvSync
function readCsvSync(filename, options) {
  const fs = require('fs');
  const parse = require('csv-parse/lib/sync');
  const content = fs.readFileSync(filename).toString();
  return parse(content, options);
}
use header
const options = { columns: true, comment: '#' };
const records = readCsvSync('sample.csv', options);
/*
[ { fruit: 'apple' },
  { fruit: 'orange' },
  { fruit: 'lemon' } ]
*/
indicate columns
const options = { columns: ['id'], comment: '#' };
const records = readCsvSync('sample.csv', options);
/*
[ { id: 'fruit' },
  { id: 'apple' },
  { id: 'orange' },
  { id: 'lemon' } ]
*/

TSVファイル読み込み

Excelで作成した、ヘッダ付きリストをコピーしてそのまま貼り付けたタブ区切りのTSVファイルから読み込む。

const fs = require('fs')
const path = require('path')
const parse = require('csv-parse/lib/sync')

const dataset = fs.readFileSync(
  path.join(__dirname, 'dataset', 'customers.tsv'),
  'utf-8'
)

const records = parse(dataset, {
  columns: true,
  delimiter: '\t',
  skip_empty_lines: true,
  trim: true,
})

console.log(records)

オブジェクト配列からCSV文字列に変換

const stringifySync = require("csv-stringify/lib/sync");

const records = [
  { id: 1, name: "宮崎", birthday: "1985/11/30" },
  { id: 2, name: "藤岡", birthday: "1988/8/9" },
  { id: 3, name: "深田", birthday: "1982/11/2" },
  { id: 4, name: "橋本", birthday: "1999/2/3" },
  { id: 5, name: "国仲", birthday: "1979/6/9" }
];

const csvString = stringifySync(records, {
  header: true,
  columns: {
    id: "ID",
    name: "氏名",
    birthday: "生年月日"
  },
  quoted_string: true
});

console.log(csvString);
/* =>
"ID","氏名","生年月日"
1,"宮崎","1985/11/30"
2,"藤岡","1988/8/9"
3,"深田","1982/11/2"
4,"橋本","1999/2/3"
5,"国仲","1979/6/9"
*/