Javascript 在 Node.js 中写入 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10227107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:24:19  来源:igfitidea点击:

Write to a CSV in Node.js

javascriptnode.jscsv

提问by Phil Bottomley

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

我正在努力寻找一种在 Node.js 中将数据写入 CSV的方法。

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

有几个 CSV 插件可用,但它们只能“写入”到标准输出。

Ideally I want to write on a row-by-rowbasis using a loop.

理想情况下,我想使用循环逐行写入。

采纳答案by Joe White

The docs for node-csv-parser(npm install csv) specifically state that it can be used with streams (see fromStream, toStream). So it's not hard-coded to use stdout.

node-csv-parser( npm install csv)的文档特别指出它可以与流一起使用(请参阅fromStream, toStream)。所以使用标准输出并不是硬编码的。

Several other CSV parsers also come up when you npm search csv-- you might want to look at them too.

其他几个 CSV 解析器也会出现在您npm search csv-- 您可能也想查看它们时。

回答by John Vandivier

You can use fs (https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):

您可以使用 fs ( https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):

var dataToWrite;
var fs = require('fs');

fs.writeFile('form-tracking/formList.csv', dataToWrite, 'utf8', function (err) {
  if (err) {
    console.log('Some error occured - file either not saved or corrupted file saved.');
  } else{
    console.log('It\'s saved!');
  }
});

回答by cbaigorri

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

这是一个使用csv-stringify将适合内存的数据集写入 csv 文件的简单示例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.');
  });
});

回答by Centillion

If you want to use a loop as you say you can do something like this with Node fs:

如果你想像你说的那样使用循环,你可以用 Node fs 做这样的事情:

let fs = require("fs")

let writeStream = fs.createWriteStream('/path/filename.csv')

someArrayOfObjects.forEach((someObject, index) => {     
    let newLine = []
    newLine.push(someObject.stringPropertyOne)
    newLine.push(someObject.stringPropertyTwo)
    ....

    writeStream.write(newLine.join(',')+ '\n', () => {
        // a line was written to stream
    })
})

writeStream.end()

writeStream.on('finish', () => {
    console.log('finish write stream, moving along')
}).on('error', (err) => {
    console.log(err)
})