Node.js 的 CSVParse 入门(csv-parse npm 包)
发布: (2026年2月13日 GMT+8 17:07)
2 分钟阅读
原文: Dev.to
Source: Dev.to
安装
npm i csv-parse
示例 CSV (data.csv)
name,age,email
Alex,33,alex@example.com
Bekky,20,bekky@example.com
Carl,27,carl@example.com
使用流解析 CSV
import fs from 'node:fs';
import { parse } from 'csv-parse';
const records = [];
fs.createReadStream('path/data.csv')
.pipe(
parse({
columns: true, // use first row as header
skip_empty_lines: true,
})
)
.on('data', (row) => {
records.push(row);
})
.on('error', (err) => {
console.error(err.message);
})
.on('end', () => {
console.log(records);
});
结果
[
{ "name": "Alex", "age": "33", "email": "alex@example.com" },
{ "name": "Bekky", "age": "20", "email": "bekky@example.com" },
{ "name": "Carl", "age": "27", "email": "carl@example.com" }
]
Parse API
parse(input, options, callback);
- input:
string或Buffer,包含 CSV 数据。 - options(可选):解析规则,例如
{ columns: true, delimiter: ',' }。 - callback:
(err, records)—— 接收错误(如果有)和解析后的记录。
性能建议
- 使用
fs.createReadStream()将大文件分块流式读取,避免一次性将整个文件加载到内存中。 - 对于小文件(≤ 5 MB),使用
fs.readFile()也是可以接受的。