0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

typescriptでcsv読み書き

0
Posted at

typescriptでcsvを読み込み、1行追加して書き込む

・fast-csvライブラリを使用する
https://c2fo.io/fast-csv/docs/introduction/getting-started

install
yarn add fast-csv
import { parseFile, writeToPath } from "fast-csv";

interface CsvFormat {
    id: number,
    name: string,
}


// fast-csvで用意されているparseFileを使ってcsvを型指定で読み込む。
// asyncが用意されていないのでPromiseでラップ
const parseAsync = (path: string) => new Promise<CsvFormat[]>(resolve => {
    const stream = parseFile(path, { headers: true})

    const data: CsvFormat[] = []
    stream.on('data', (row: CsvFormat) => {
        data.push(row)
    })

    stream.on('end', () => {
        resolve(data)
    })
})

// 読み込み ~ 書き込み
const test = async () => {
    const path = '/path/to/csv.csv'
    const list = await parseAsync(path)

    const newItem : CsvFormat = {
        id: 9999,
        name: 'hoge',
    }

    list.push(newItem)

    // csvに書き込む
    writeToPath(path, list, { headers: true , alwaysWriteHeaders: true })
}
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?