【问题标题】:node csv parsing return value comes back as undefined when called [duplicate]节点csv解析返回值在调用时返回为未定义[重复]
【发布时间】:2021-11-03 18:34:29
【问题描述】:

这是我正在运行的代码

const fs = require('fs');
const csvParse = require('csv-parse');

function getValue() {
    let results = [];
    fs.createReadStream('./assets/myCSV.csv')
        .pipe(csvParse({delimiter: '\n'}))
        .on('data', (data) => results.push(data))
        .on('error', (err => {
            console.log(`csv-parse error from getValue: ${err}`);
        }))
        .on('end', () => {
            console.log('finished!');

            let csvLength = Object.keys(results).length;

            // getting a random value within the csv
            min = Math.ceil(0);
            max = Math.floor(csvLength);
            let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

            let randomCSVLine = results[randomNumber];

            console.log(randomCSVLine);

            return randomCSVLine;
        });
}

console.log(`mine: ${getValue()}`);

这是结果,我不知道为什么没有显示值。我认为这可能是一个异步问题,但不确定如何解决它:

mine: undefined
finished!
[ '10' ]

【问题讨论】:

    标签: javascript node.js csv


    【解决方案1】:

    我想你会在这里找到解决方案。

    CSV Parser for Node.js Promises usage

    从 Node.js 版本 15 开始,Stream API 承诺一个新的“stream/promises”模块。

    Stream Promises 模块的一部分是完成的函数。当函数不再可读、可写或遇到错误或过早关闭事件时,函数会插入流并解析承诺。

    promise 示例利用 pipe 和 finished 提供了一种方便的解决方案,可以从文件系统读取文件并将其输出通过管道传输到解析器。

    此示例可通过命令 node samples/recipe.promises.js 获得。

    const parse = require('csv-parse');
    const fs = require('fs');
    const { finished } = require('stream/promises');
     
    const processFile = async () => {
      records = []
      const parser = fs
      .createReadStream(`${__dirname}/fs_read.csv`)
      .pipe(parse({
        // CSV options if any
      }));
      parser.on('readable', function(){
        let record;
        while (record = parser.read()) {
          // Work with each record
          records.push(record)
        }
      });
      await finished(parser);
      return records
    }
    
    (async () => {
      const records = await processFile()
      console.info(records);
    })()
    

    只需对您的代码进行相同的更改即可获得所需的结果。

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2019-05-24
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多