Write to a CSV in Node.js

前端 未结 6 1151
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 14:47

I am struggling to find a way to write data to a CSV in Node.js.

There are several CSV plugins available however they only \'write\' to stdout.

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 14:57

    Here is a simple example using csv-stringify to write a dataset that fits in memory to a csv file using fs.writeFile.

    import stringify from 'csv-stringify';
    import fs from 'fs';
    
    let data = [];
    let columns = {
      id: 'id',
      name: 'Name'
    };
    
    for (var i = 0; i < 10; i++) {
      data.push([i, 'Name ' + i]);
    }
    
    stringify(data, { header: true, columns: columns }, (err, output) => {
      if (err) throw err;
      fs.writeFile('my.csv', output, (err) => {
        if (err) throw err;
        console.log('my.csv saved.');
      });
    });
    

提交回复
热议问题