1
0

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 1 year has passed since last update.

fast-csvでjsonをcsvに変換する

Last updated at Posted at 2022-01-30

はじめに

表題のとおり。サーバーサイドでjsonをcsvに変換します。
クライアントサイドで同じことをするためには別の方法が必要です。

実装

index.ts
import * as fs from 'fs';
import * as path from 'path';
import { format } from '@fast-csv/format';

const createCsv = async () => {
  const fileName = 'test.csv';
  const filePath = path.resolve(__dirname, 'csv');
  fs.access(filePath, (error) => {
    if (error) {
      fs.mkdirSync(filePath);
    }
  });

  const jsonData = [{id: 1, name: 'hoge'}, {id: 2, name: 'fuga'}];
  const ws = fs.createWriteStream(path.resolve(__dirname, 'temp', fileName));
  const stream = format({ headers: true});
  stream.pipe(ws).on('finish', () => {
    console.log(`#### ${fileName} has been successfully created! ####`);
  });
  await Promise.all(jsonData.map((row) => stream.write(row)));
};

createCsv().catch((e) => console.error(e));
$ ts-node index.ts

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?