csv
注意
这是一个实验性模块。
虽然我们力求保持实验性模块的稳定性,但可能需要引入破坏性变更。在未来的 k6 版本中,这种情况可能会发生,直到该模块完全稳定并升级为 k6 核心模块。更多信息,请参阅扩展正式化流程。
实验性模块保持了高度的稳定性,并遵循常规的维护和安全措施。欢迎提交 issue如果您有任何反馈或建议。
k6-experimental/csv
模块提供了处理 k6 中 CSV 文件的有效方法,与传统的基于 JavaScript 的库相比,它提供了更快的解析速度和更低的内存使用量。
此模块包含整文件解析和流式处理功能,允许用户在性能和内存优化之间进行选择。
主要功能
- 该
csv.parse()
函数将完整的 CSV 文件解析为 SharedArray,利用基于 Go 的处理方式,与 JavaScript 替代方案相比,可提供更好的性能并减少内存占用。 - 该
csv.Parser
类是一个流式解析器,逐行读取 CSV 文件,优化内存使用,并通过类似流的 API 提供对解析过程的更多控制。
优点
- 更快的解析速度:该
csv.parse()
函数绕过了 JavaScript 运行时,显著加快了大型 CSV 文件的解析速度。 - 更低的内存使用:当使用
fs.open()
函数时,csv.parse()
和csv.Parser
都支持跨虚拟用户(VU)共享内存。 - 灵活性:用户可以选择使用
csv.parse
进行整文件解析以提高速度,或使用csv.Parser
进行逐行流式处理以提高内存效率。
权衡
- 该
csv.parse()
函数在初始化阶段解析整个文件,这可能会增加大型文件的启动时间和内存使用。最适用于性能比内存消耗更重要的场景。 - 该
csv.Parser
类逐行处理文件,因此内存效率更高,但由于读取每一行的开销,速度可能会慢一些。适用于内存使用至关重要或需要更精细控制解析过程的场景。
API
函数/对象 | 描述 |
---|---|
parse | 将整个 CSV 文件解析到 SharedArray 中,适用于高性能场景。 |
Parser | 一个用于流式 CSV 解析的类,支持逐行读取,内存消耗极低。 |
选项 | 一个对象,描述了使用parse() 函数和csv.Parser 类解析 CSV 文件的可用配置。 |
示例
将完整的 CSV 文件解析到 SharedArray 中
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, { delimiter: ',' });
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.
//
// Thus, `csvRecords[scenario.iterationInTest]` will give us the record for the current iteration.
console.log(csvRecords[scenario.iterationInTest]);
}
逐行流式处理 CSV 文件
import { open } from 'k6/experimental/fs';
import csv from 'k6/experimental/csv';
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 parser = new csv.Parser(file);
export default async function () {
// The parser `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);
}