我有一个模块,可以使用Promise将CSV转换为JSON,因为我使用了Promise而不是返回数据。现在的数据是隐式的,我无法比较两个CSV文件。如何将代码更改为使用return语句。
csv到json文件
const readline = require('readline');
const fs = require('fs');
function readCsv(pathToFile) {
return new Promise((resolve, reject) => {
// This is where your code would go (other than the "requires")
// replace the "cats.csv" string with the "pathToFile" variable instead
// stick this inside of your "close" handler function once the data's been assembled:
const csvReader = readline.createInterface({
input: fs.createReadStream(pathToFile)
});
let headers;
const rows = [];
let tempRows = [];
csvReader
.on('line', row => {
if (!headers) {
headers = row.split(','); // header name breed age
} else {
rows.push(row.split(','));
}
})
.on('close', () => {
// then iterate through all of the "rows", matching them to the "headers"
for (var i = 0; i < rows.length; i++) {
var obj = {};
var currentline = rows[i];
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j]; //Kitty Siamese 14
}
tempRows.push(obj);
}
resolve(JSON.stringify(tempRows));
});
// This would be in place of the "return" statement you had before
});
}
module.exports = readCsv;