はじめに
表題のとおり。サーバーサイドで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