【问题标题】:Understanding Node / promise in reading a csv to an array (getting values out of the promise)在将 csv 读取到数组时理解节点/承诺(从承诺中获取值)
【发布时间】:2020-02-20 02:21:36
【问题描述】:

我想将 .csv 文件读入数组,获取读取的行数,然后将数组发送到另一个函数以进行额外处理。

我搜索并找到了一些有效的示例代码(除了能够从承诺中获取值)。

const csv = require('csv-parser')

async function readCsv(csv_file_path) {

    const list = []     // read .csv into array (list)
    var num_rows = 0    // the number of rows read

    fs.createReadStream(csv_file)
        .pipe(csv())
        .on('data', (data) => list.push(data))
        .on('end', () => {
            num_rows = list.length
            console.log('num_rows', num_rows) // prints num rows read, fine
        })

    // now, here, at this point in the code, I want to use:
    //  1. num_rows
    //  2. address_list outside fo the fs.createReadStream function
    // how do I do this?

    // Here, outside, num_rows is 0, and nothing is in the list
    console.log('num_rows:', num_rows)
    for (let address of address_list) {
        console.log('address:', address);
    }

    // how do I get the value for num_rows, and contents of list[] set,
    // so I can use here at this point in the code?
}

【问题讨论】:

    标签: node.js csv promise es6-promise


    【解决方案1】:

    我建议你使用一个库来解析.csv。一个好的是csv-parse,您可以使用npm 安装它。

    这是一个使用同步 API 的简单示例。

    const parse = require('csv-parse/lib/sync')
    
    const input = `
    "key_1","key_2"
    "value 1","value 2"
    "value 3","value 3"
    `
    const records = parse(input, {
      skip_empty_lines: true
    })
    
    console.log(records)
    
    // Output:
    // [ [ 'key_1', 'key_2' ],
    // [ 'value 1', 'value 2' ],
    // [ 'value 3', 'value 3' ] ]
    // Just get the length of the output array to get the number of rows in the file
    

    您可以找到 API 文档 here

    【讨论】:

    • 解析 .csv 不是问题,正如您在我发布的代码中看到的那样,我成功地做到了这一点。我在解析 .csv 时没有问题。您误会了,这不是处理解析.csv 问题的帖子,请再次阅读问题。为了将来参考,请避免无助于接近解决方案的响应。它污染了问题/发布,浪费了那些搜索的时间,并且可能会发现这一点,将来会遇到同样的问题。请删除您的答案。
    猜你喜欢
    • 2017-05-29
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2018-12-24
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多