嗨,我有两个CSV文件。
Spas.csv
id | name
...........................
5 | Wasana spa
...........................
7 | Hot spring spa
...........................
8 | Colombo spa
...........................
10 | Sanhida spa
...........................
12 | Waruna spa
...........................
Customers.csv
id | name | spaId
........................
1 |Hiran |5
........................
2 |Hirushi|5
........................
3 |Mishani|8
........................
4 |Chamod |12
从MYSQL DB
导出的这两个CSV文件。
我想要的是像这样更改spaId
文件的Customers.csv
。
id | name | spaId
........................
1 |Hiran |1
........................
2 |Hirushi|1
........................
3 |Mishani|3
........................
4 |Chamod |5
这些新的spaId来自 Spas.csv 文件的行号。 示例:-id 5位于行1,因此将5替换为1。
如何在nodejs / javaScript中实现此目的。我到目前为止所做的就是这个。
var fs = require('fs')
var csv = require('fast-csv');
fs.createReadStream('spas.csv')
.pipe(csv())
.on('data',function(data){
console.log('DATA',data)
})
.on('end',function(data){
console.log("FIN",data)
})
基本上,它将控制台记录每一行作为数组,我不知道如何同时写入CSV。
答案 0 :(得分:0)
尝试一下:
const fs = require("fs");
const csv = require("fast-csv");
async function getSpasIdMap(filePath){
return new Promise(function(resolve, reject) {
let map = {};
let count = 0;
let stream = fs.createReadStream(filePath);
let csvStream = csv({ headers:true })
.on("data", function(data){
map[data.id] = ++count;
})
.on("error", (e) => {
reject(e);
})
.on("end", function(){
resolve(map);
});
stream.pipe(csvStream);
})
}
async function computeAndWriteCustomerData(spasSource, customerSource, dest){
let spasMap = await getSpasIdMap(spasSource);
let customerStream = fs.createReadStream(customerSource);
let csvCustomerStream = csv({headers:true})
.transform(function(row) {
return `${row.name},${spasMap[row.spaId]}\n`;
});
let writableStream = fs.createWriteStream(dest);
customerStream.pipe(csvCustomerStream);
csvCustomerStream.pipe(writableStream);
}
async function main() {
await computeAndWriteCustomerData("spas.csv", "customer.csv", "my.csv");
}
main();