LoginSignup
7
4

More than 5 years have passed since last update.

【TypeScript】TypeScriptでNode.jsを使ってCSVを読み込む

Posted at

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' ] ]
7
4
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
7
4