【发布时间】: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