node.js - 在将 csv 读取到数组时理解 Node / Promise(从 Promise 中获取值)
问题描述
我想将 .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?
}
解决方案
我建议您使用库进行.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 文档。
推荐阅读
- python - 递归函数在 False 条件下运行,返回 None
- ios - 我如何从 struct 获取纬度和经度并在 mapbox Swift 上显示它们
- unity3d - 如何防止非触发碰撞器在 Unity 中相互推动?
- storybook - 开玩笑不识别 mdx 文件
- c++ - 电子应用程序从本机 C 代码创建的访问窗口
- ios - 如何通过 Xcode 构建设置传递额外的 xcodebuild 标志
- sql-server - 我无法在此 SQL 语句中应用多个条件
- html - 在 NodeJS 中将 HTML 转换为 PDF 或 PNG,而无需无头浏览器实例
- node.js - 在 Oracle 云计算实例上打开 3000 端口
- php - XAMPP:错误 404 找不到对象!调用 API 时在此服务器上未找到请求的 URL