[英]Read a CSV file line-by-line using node.js and ES6/ES7 features
Reading a CSV file line-by-line (ie without loading the whole file into memory) in Python is simple: 在Python中逐行读取CSV文件(即不将整个文件加载到内存中)很简单:
import csv
for row in csv.reader(open("file.csv")):
print(row[0])
Doing the same with node.js involves using something like node-csv , streams and callbacks. 对node.js执行相同操作涉及使用node-csv ,streams和callbacks之类的东西。
Is it possible to use new ES6/ES7 features like iterators, generators, promises and async functions to iterate over lines of a CSV file in a way that looks more like the Python code? 是否可以使用新的ES6 / ES7功能(如迭代器,生成器,承诺和异步函数)以更像Python代码的方式迭代CSV文件的行?
Ideally I'd like to be able to write something like this: 理想情况下,我希望能够写出这样的东西:
for (const row of csvOpen('file.csv')) {
console.log(row[0]);
}
(again, without loading the whole file into memory at once.) (同样,不要立即将整个文件加载到内存中。)
I'm not familiar with node-csv, but it sounds like an iterator using a generator should do it. 我不熟悉node-csv,但听起来像使用生成器的迭代器应该这样做。 Just wrap that around any asynchronous callback API:
只需将其包装在任何异步回调API周围:
let dummyReader = {
testFile: ["row1", "row2", "row3"],
read: function(cb) {
return Promise.resolve().then(() => cb(this.testFile.shift())).catch(failed);
},
end: function() {
return !this.testFile.length;
}
}
let csvOpen = url => {
let iter = {};
iter[Symbol.iterator] = function* () {
while (!dummyReader.end()) {
yield new Promise(resolve => dummyReader.read(resolve));
}
}
return iter;
};
async function test() {
// The line you wanted:
for (let row of csvOpen('file.csv')) {
console.log(await row);
}
}
test(); // row1, row2, row3
var failed = e => console.log(e.name +": "+ e.message);
Note that row
here is a promise, but close enough. 请注意,这里的
row
是一个承诺,但足够接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.