Parser
csv.Parser
类提供了一个流式解析器,逐行读取 CSV 文件,对解析过程提供细粒度控制,并最大限度地减少内存消耗。它非常适合内存效率至关重要的场景,或者需要在不将整个文件加载到内存中的情况下处理大型 CSV 文件。
构造函数
参数 | 类型 | 描述 |
---|---|---|
file | fs.File | 使用 fs.open 函数打开的文件实例。 |
options | 选项 | 一个可选的参数对象,用于自定义解析行为。选项可以包括分隔符 (delimiter)(字符串)。 |
方法
名称 | 描述 |
---|---|
next() | 从 CSV 文件中读取下一行,并返回一个解析为类似迭代器对象的 Promise。 |
返回值
一个解析为包含以下属性的对象的 Promise
属性 | 类型 | 描述 |
---|---|---|
done | boolean | 指示是否还有更多行可读(false)或已到达文件末尾(true)。 |
value | string[] | 包含 CSV 记录的字段作为字符串数组。如果 done 为 true,则 value 为 undefined。 |
示例
基本用法
import { open } from 'k6/experimental/fs';
import csv from 'k6/experimental/csv';
export const options = {
iterations: 10,
};
const file = await open('data.csv');
const parser = new csv.Parser(file, { skipFirstLine: true });
export default async function () {
// The `next` method attempts to read the next row from the CSV file.
//
// It returns an iterator-like object with a `done` property that indicates whether
// there are more rows to read, and a `value` property that contains the row fields
// as an array.
const { done, value } = await parser.next();
if (done) {
throw new Error('No more rows to read');
}
// We expect the `value` property to be an array of strings, where each string is a field
// from the CSV record.
console.log(done, value);
}
使用 asObjects
asObjects
选项将 CSV 文件解析为对象数组。对象键是 CSV 文件中的列名,值是 CSV 记录中的字段值。请注意,CSV 文件的第一行会被跳过,因为它被假定包含列名(标题行)。
import { open } from 'k6/experimental/fs';
import csv from 'k6/experimental/csv';
import { scenario } from 'k6/execution';
export const options = {
iterations: 3,
};
const file = await open('data.csv');
const parser = new csv.Parser(file, { asObjects: true });
export default async function () {
// Will print the record for the current iteration as an object.
//
// For example, given the following CSV file:
//
// firstname,lastname
// francois,mitterand
// helmut,kohl
// pierre,mendes-france
//
// The test will print:
//
// { firstname: 'francois', lastname: 'mitterand' }
// { firstname: 'helmut', lastname: 'kohl' }
// { firstname: 'pierre', lastname: 'mendes-france' }
const { done, value } = await parser.next();
if (done) {
throw new Error('No more rows to read');
}
console.log(value);
}
使用注意事项
- 内存效率:由于
csv.Parser
逐行读取文件,因此可以保持较低的内存使用率,并避免将所有记录加载到内存中。这对于大型 CSV 文件特别有用。 - 流式控制:流式处理方法提供了对记录处理方式的更多控制,这对于复杂的数据处理需求可能很有益。