简体   繁体   English

如何使用 csv-parse 避免等待...

[英]How to avoid for await...of with csv-parse

I am looking to be educated on this issue as I have spent a few days trying to resolve it on my own, to no avail.我希望在这个问题上接受教育,因为我花了几天时间试图自己解决它,但无济于事。

I am using csv-parse to parse a CSV file.我正在使用csv-parse来解析 CSV 文件。
I am using ESLint as my Linter我使用ESLint作为我的 Linter
I am using the Airbnb JavaScript Style Guide plugin for ESLint我正在使用 ESLint 的Airbnb JavaScript Style Guide插件
I am running this on the backend using NodeJS我正在使用 NodeJS 在后端运行它

My function is:我的 function 是:

const { parse } = require('csv-parse');
const fs = require('fs');
const csvFile = 'myCsvFile.csv';

async function parseCsv(csvFile) {
  const records = [];
  const parser = fs.createReadStream(csvFile).pipe(parse({ delimiter: ',', columns: true }));
  for await (const record of parser) {
    records.push(record);
  }
  return records;

The function works well, however I am trying to abide by Airbnb's Style Guide, which does not like the for await...of loop as it is hitting me with the no-restricted-syntax violation. function 运行良好,但是我试图遵守 Airbnb 的样式指南,它不喜欢for await...of循环,因为它违反了no-restricted-syntax违规行为。

I am curious on if there is a better way to write this to fall in line with Airbnb's Style Guide or, if this is one of those situations where it's OK to ignore the violation?我很好奇是否有更好的方法来写这篇文章以符合 Airbnb 的风格指南,或者,如果这是可以忽略违规的情况之一?

The styleguide says:风格指南说:

11.2 Don't use generators for now. 11.2 暂时不要使用生成器。 Why?为什么? They don't transpile well to ES5.它们不能很好地转换为 ES5。

Fortunately if you're using a recent NodeJS version, you don't need to transpile down, and can use the engine's native support.幸运的是,如果您使用的是最新的 NodeJS 版本,则无需向下转换,并且可以使用引擎的原生支持。 For browsers this advice is also outdated soon.对于浏览器,这个建议也很快就过时了。

How about using events end returning promise?使用事件结束返回 promise 怎么样?

async function parseCsv(csvFile) {
  return new Promise((resolve) => {
    const records = [];
    const stream = fs.createReadStream(csvFile);
    const parser = stream.pipe(parse({ delimiter: ',', columns: true }));
    
    parser.on('readable', () => {
      while (record = parser.read()) {
        records.push(record);
      }
    });

    let ended = false;

    parser.on('error', (error) => {
      console.error(error.message);
      if (!ended) {
        ended = true;
        resolve(records);
      }
    });

    parser.on('end', () => {
      if (!ended) {
        ended = true;
        resolve(records);
      }
    });
  });
}

Based on advice given in the answers, I am going to ignore the Airbnb Style Guide and use the Async iterator method.根据答案中给出的建议,我将忽略Airbnb 样式指南并使用异步迭代器方法。

Final code:最终代码:

const { parse } = require('csv-parse');
const fs = require('fs');
const path = require('path');
const debug = require('debug')('app:csv:service');
const chalk = require('chalk');

async function parseCsv(csvFile) {
  try {
    const records = [];
    const stream = fs.createReadStream(csvFile);
    const parser = stream.pipe(parse({ delimiter: ',', columns: true }));
    // eslint-disable-next-line no-restricted-syntax
    for await (const record of parser) {
      records.push(record);
    }
    return records;
  } catch (error) {
    debug(`${chalk.red('Failed')} to parse CSV`);
    debug(`${chalk.red('ERROR:')} ${error}`);
    throw error;
  }
}

It may be time to find a new Style Guide to follow.可能是时候寻找一个新的风格指南来遵循了。 Thank you to num8er for the code advice (I took one of your ideas to make my code a little more readable).感谢num8er的代码建议(我采纳了您的一个想法,使我的代码更具可读性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM