使用node.js和ES6 / ES7功能逐行读取CSV文件 [英] Read a CSV file line-by-line using node.js and ES6/ES7 features

查看:288
本文介绍了使用node.js和ES6 / ES7功能逐行读取CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中逐行读取CSV文件(即不将整个文件加载到内存中)很简单:

Reading a CSV file line-by-line (i.e. without loading the whole file into memory) in Python is simple:

import csv
for row in csv.reader(open("file.csv")):
    print(row[0])

对node.js执行相同操作涉及使用类似 node-csv ,流和回调。

Doing the same with node.js involves using something like node-csv, streams and callbacks.

是否可以使用新的ES6 / ES7功能,如迭代器,生成器,承诺和async函数以一种看起来更像Python代码的方式迭代CSV文件的行?

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?

理想情况下,我希望能够写出这样的东西:

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.)

推荐答案

我不熟悉node-csv,但听起来像使用生成器的迭代器应该这样做。只需将其包装在任何异步回调API周围:

I'm not familiar with node-csv, but it sounds like an iterator using a generator should do it. Just wrap that around any asynchronous callback 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.

将其粘贴在 babel

这篇关于使用node.js和ES6 / ES7功能逐行读取CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆