open( filePath, [mode] )
打开一个文件,将所有内容读入内存以供脚本使用。
注意
open()
只能从 初始化上下文 (init context) 中调用。此限制对于确定在多个节点上分发测试时需要打包的本地文件是必要的。
提示
open()
通常会消耗大量内存,因为每个 VU 都会在内存中保留文件的单独副本。为了减少内存消耗,您可以:
- 在 SharedArray 中使用
open()
,这样 VU 之间可以共享分配的文件内存。- 使用
k6/experimental/fs
模块中的 open()。它提供了一种内存效率更高的方式来处理测试脚本中的文件交互,并且可以以小块读取文件。
参数 | 类型 | 描述 |
---|---|---|
filePath | string | 要读入内存的文件路径(绝对或相对)。即使在运行多个 VU 时,文件也只加载一次。 |
mode | string | 默认情况下,文件内容按文本读取,但如果您指定 b ,文件将按二进制数据读取。 |
返回值
类型 | 描述 |
---|---|
string / ArrayBuffer | 文件内容,以字符串或 ArrayBuffer(如果指定了 b 模式)形式返回。 |
示例
[
{
"username": "user1",
"password": "password1"
},
{
"username": "user2",
"password": "password2"
},
{
"username": "user3",
"password": "password3"
}
]
import { SharedArray } from 'k6/data';
import { sleep } from 'k6';
const data = new SharedArray('users', function () {
// here you can open files, and then do additional processing or generate the array with data dynamically
const f = JSON.parse(open('./users.json'));
return f; // f must be an array[]
});
export default () => {
const randomUser = data[Math.floor(Math.random() * data.length)];
console.log(`${randomUser.username}, ${randomUser.password}`);
sleep(3);
};
import { sleep } from 'k6';
const users = JSON.parse(open('./users.json')); // consider using SharedArray for large files
export default function () {
const user = users[__VU - 1];
console.log(`${user.username}, ${user.password}`);
sleep(3);
}
import http from 'k6/http';
import { sleep } from 'k6';
const binFile = open('/path/to/file.bin', 'b');
export default function () {
const data = {
field: 'this is a standard form field',
file: http.file(binFile, 'test.bin'),
};
const res = http.post('https://example.com/upload', data);
sleep(3);
}