使用Node.js中的fast-csv包读取和写入CSV [英] Read and Write CSV using fast-csv package in Node.js
问题描述
我正在尝试编写一个简单的节点程序,该程序读取csv文件,提取一列(例如第二列),然后将其写入另一个CSV文件。我正在将内容读取到数组,然后将该数组写入文件。
I am trying to write a simple node program that reads a csv file, extracts a column (say second) and writes it to another CSV file. I am reading the contents to an array and then writing that array to file.
每个步骤中的阶段和数据
Stages and data in each step
输入文件
123,456,789,abc
def,ghi,232,jkl
数组
['456','ghi']
输出文件
4,5,6
g,h,i
需要的输出
456
ghi
我只是缺少配置,还是写数据的方式错误?我的END块中要写入文件的代码块不正确吗?
Am i just missing a configuration or is the way i am writing data wrong? Is my block of code to write to file within END block not correct?
这是我的代码
var fast_csv = require('fast-csv');
var tempArray=new Array();
console.log("START");
fast_csv.fromPath("inputfile.txt").on("data", function(data){
tempArray.push(data[1]);
})
.on("end", function(){
tempArray.sort();
console.log(tempArray);
fast_csv.writeToPath("outputfile.csv", tempArray)
.on("finish", function(){
console.log("END");
});
});
推荐答案
它将数组中的每个元素都视为一个数组,因此 456被视为包含元素4,5,6的数组。
It treats each element in the array as an array, so '456' is treated as an array with the elements 4,5,6.
我做过的一个奇怪的解决方法是遍历数组并将每个元素放入其内部自己的数组,所以它将是:
A strange workaround I did was to loop through the array and put each element inside its own array, so it would be:
var newArray = [];
for( var i = 0; i < tempArray.length; i++){
var arr = [];
arr.push(tempArray[i]);
newArray.push(arr);
}
然后写 newArray。
And then write the "newArray".
但是如果您逐行编写,则可以将每个元素放在方括号内,例如:
But otherwise if you write row by row, you can put each element inside a bracket, like:
var fast_csv = fastcsv.createWriteStream();
var writeStream = fs.createWriteStream("outputfile.csv");
fast_csv.pipe(writeStream);
for(var i = 0; i < tempArray.length; i++){
fast_csv.write( [ tempArray[i] ] ); //each element inside bracket
}
fast_csv.end();
这篇关于使用Node.js中的fast-csv包读取和写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!