parse( 文件, [选项] )
csv.parse
函数一次性解析整个 CSV 文件,并返回一个 Promise,该 Promise 解析为一个 SharedArray 实例。此函数使用基于 Go 的处理,与 JavaScript 替代方案相比,解析速度更快且内存使用更低。它非常适合性能优先且整个 CSV 文件可以加载到内存中的场景。
参数
参数 | 类型 | 描述 |
---|---|---|
file | fs.File | 使用 fs.open 函数打开的文件实例。 |
options | 选项 | 用于自定义解析行为的可选参数对象。 |
返回值
解析为 SharedArray 实例的 Promise,其中每个元素是一个表示 CSV 记录的数组,每个子元素是该记录中的一个字段。
示例
基本用法
import { open } from 'k6/experimental/fs';
import csv from 'k6/experimental/csv';
import { scenario } from 'k6/execution';
export const options = {
iterations: 10,
};
const file = await open('data.csv');
// The `csv.parse` function consumes the entire file at once and returns
// the parsed records as a `SharedArray` object.
const csvRecords = await csv.parse(file);
export default async function () {
// `csvRecords` is a `SharedArray`. Each element is a record from the CSV file, represented as an array
// where each element is a field from the CSV record.
//
// `csvRecords[scenario.iterationInTest]` gives the record for the current iteration.
console.log(csvRecords[scenario.iterationInTest]);
}
使用 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 csvRecords = await csv.parse(file, { asObjects: true });
export default 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' }
console.log(csvRecords[scenario.iterationInTest]);
}
使用注意事项
- 内存注意事项:
csv.parse
一次性将整个 CSV 文件加载到内存中,这可能会导致非常大的文件占用更多内存并增加启动时间。 - 共享内存使用:
csv.parse
返回的 SharedArray 在所有虚拟用户(VU)之间共享,当多个虚拟用户访问相同数据时,可以减少内存开销。