我正在努力寻找一种方法来在 Node.js 中将数据写入 CSV。
有几个可用的 CSV 插件,但它们只能“写入”到标准输出。
理想情况下,我想使用循环在逐行的基础上编写。
您可以使用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!');
}
});
node-csv-parser
(npm install csv
) 的文档明确指出它可以与流一起使用(请参阅fromStream
、toStream
)。所以使用 stdout 并不是硬编码的。
当您
npm search csv
时,还会出现其他几个 CSV 解析器——您可能也想看看它们。
这是一个使用 csv-stringify 的简单示例,使用
fs.writeFile
将适合内存的数据集写入 csv 文件。
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.');
});
});
如果你想像你说的那样使用循环,你可以使用 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)
})
如果您不想使用除
fs
之外的任何库,您可以手动完成。
let fileString = ''
const filename = 'fileExample.csv'
fileString += Object.keys(jsonObjects[0]).join(',')
jsonObjects.forEach((jsonObject) => {
fileString += '\n' + Object.values(jsonObject).join(',')
})
fs.writeFileSync(filename, fileString, 'utf8')
编写 CSV 非常简单,无需库即可完成。
import { writeFile } from 'fs/promises';
// you can use just fs module too
// Let's say you want to print a list of users to a CSV
const users = [
{ id: 1, name: 'John Doe0', age: 21 },
{ id: 2, name: 'John Doe1', age: 22 },
{ id: 3, name: 'John Doe2', age: 23 }
];
// CSV is formatted in the following format
/*
column1, column2, column3
value1, value2, value3
value1, value2, value
*/
// which we can do easily by
const dataCSV = users.reduce((acc, user) => {
acc += `${user.id}, ${user.name}, ${user.age}\n`;
return acc;
},
`id, name, age\n` // column names for csv
);
// finally, write csv content to a file using Node's fs module
writeFile('mycsv.csv', dataCSV, 'utf8')
.then(() => // handle success)
.catch((error) => // handle error)
注意:如果您的 CSV 内容中包含
,
,则必须将其转义或使用其他分隔符。如果是这种情况,我建议使用像 csv-stringify 这样的库
对于那些喜欢fast-csv的人:
const { writeToPath } = require('@fast-csv/format');
const path = `${__dirname}/people.csv`;
const data = [{ name: 'Stevie', id: 10 }, { name: 'Ray', id: 20 }];
const options = { headers: true, quoteColumns: true };
writeToPath(path, data, options)
.on('error', err => console.error(err))
.on('finish', () => console.log('Done writing.'));
**如果您不想使用除 fs 之外的任何库,您可以手动完成。此外,您可以根据想要写入 CSV 文件的方式过滤数据 **
router.get('/apiname', (req, res) => {
const data = arrayOfObject; // you will get from somewhere
/*
// Modify old data (New Key Names)
let modifiedData = data.map(({ oldKey1: newKey1, oldKey2: newKey2, ...rest }) => ({ newKey1, newKey2, ...rest }));
*/
const path = './test'
writeToFile(path, data, (result) => {
// get the result from callback and process
console.log(result) // success or error
});
});
writeToFile = (path, data, callback) => {
fs.writeFile(path, JSON.stringify(data, null, 2), (err) => { // JSON.stringify(data, null, 2) help you to write the data line by line
if (!err) {
callback('success');
// successfull
}
else {
callback('error');
// some error (catch this error)
}
});
}
这是在 Nest js 中为我工作的代码
import { Parser } from "json2csv";
const csv = require('csvtojson');
const csvFilePath = process.cwd() + '/' + file.path;
let csv data = await csv().fromFile(csvFilePath); /// read data from csv into an array of json
/// * from here how to write data into csv *
data.push({
label: value,
.......
})
}
const fields = [
'field1','field2', ...
]
const parser = new Parser({ fields, header:false }); /// if dont want header else remove header: false
const csv = parser.parse(data);
appendFileSync('./filename.csv',`${csv}\n`); // remove /n if you dont want new line at the end