NodeJS - 读取CSV文件到数组返回[]

时间:2018-03-30 16:29:09

标签: node.js

我正在尝试使用promised-csv模块(https://www.npmjs.com/package/promised-csv)将CSV文件的行读取到字符串数组以进行单元测试:

const inputFile = '.\\test\\example_result.csv';
const CsvReader = require('promised-csv');

function readCSV(inputFile){
   var reader = new CsvReader();
   var output = [];
   reader.on('row', function (data) {
       //console.log(data);
       output.push(data[0]);
   });

  reader.read(inputFile, output);
  return output;
}

我想稍后在单元测试中调用此函数。

it("Should store the elements of the array", async () => {
   var resultSet = readCSV(inputFile);
   console.log(resultSet);
});

但是,resultSet会产生一个空数组。我也可以使用任何其他模块,只要我可以得到一个字符串数组。

2 个答案:

答案 0 :(得分:1)

根据文档,代码看起来应该是这样的。

const inputFile = './test/example_result.csv';
const CsvReader = require('promised-csv');

function readCSV(inputFile) {
    return new Promise((resolve, reject) => {

        var reader = new CsvReader();
        var output = [];

        reader.on('row', data => {
            // data is an array of data. You should
            // concatenate it to the data set to compile it.
            output = output.concat(data);
        });

        reader.on('done', () => {
            // output will be the compiled data set.
            resolve(output);
        });

        reader.on('error', err => reject(err));

        reader.read(inputFile);

    });
}

it("Should store the elements of the array", async () => {
    var resultSet = await readCSV(inputFile);
    console.log(resultSet);
});

答案 1 :(得分:0)

readCSV()返回一个Promise。有两种方法可以访问它在完成时返回的数据。

  1. 正如Roland Starke建议的那样,使用asyncawait
  2. var resultSet = await readCSV(inputFile); 这将在返回值之前等待Promise解析。

    更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    1. 使用Promise.prototype.then() - 这类似于async / await,但也可以与其他promises和Promise.prototype.catch()链接。 要记住的最重要的事情是,在.then()解决之前,传递给readCSV()的函数不会被执行。
    2. readCSV().then((data)=>{return data}).catch((err)=>{console.log(err)})

      更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then