TypeScriptでCSVを読み込みたかったのでメモ。
TypeScriptとかクラスとか全然知らないけど,とりあえず読めればいいや的な扱いで。
sample.csv
var1,var2,var3
val11,val21,val31
val12,val22,val32
val13,val23,val33
val14,val24,val34
val15,val25,val35
read_csv.ts
import * as fs from 'fs';
import csvSync = require('csv-parse/lib/sync');
class DataProcess {
// Read CSV as 2-D list.
static readCsv(input: string) {
const data = fs.readFileSync(input);
const matrix = csvSync(data);
return matrix;
}
}
// Run.
const csv = DataProcess.readCsv('./sample.csv');
console.log(csv);
tsc read_csv.ts
node read_csv.js
[ [ 'var1', 'var2', 'var3' ],
[ 'val11', 'val21', 'val31' ],
[ 'val12', 'val22', 'val32' ],
[ 'val13', 'val23', 'val33' ],
[ 'val14', 'val24', 'val34' ],
[ 'val15', 'val25', 'val35' ] ]