使用相对路径时K6的open函数抛出路径不存在错误
问题描述
以下是K6官方示例代码:
import { SharedArray } from 'k6/data'; const data = new SharedArray('some name', function () { // 耗时操作应放在此处,仅执行一次并在所有VU间共享 const f = JSON.parse(open('..\\inputs\\sample.json')); return f; // 返回值必须是数组 }); export default function () { const element = data[Math.floor(Math.random() * data.length)]; console.log(element); }
实际测试时,在SharedArray的回调(init上下文)中使用相对路径调用open函数会抛出路径不存在错误,而使用绝对路径则正常运行。报错信息如下:
ERRO[0000] GoError: CreateFile inputs\sample.json: The system cannot find the path specified.
at go.k6.io/k6/js.(*Bundle).setInitGlobals.func3 (native)
at file:///-:28:28(5)
at file:///-:27:12(46) hint="script exception"
问题原因
在Windows系统下,K6的open函数在init上下文处理相对路径时,解析基准是执行k6命令的工作目录,而非脚本文件所在的目录。如果执行命令时的工作目录与脚本目录不一致,就会导致相对路径指向错误的位置。
解决方法
方法1:使用绝对路径
直接传入文件的绝对路径,示例:
const f = JSON.parse(open('C:/project/inputs/sample.json'));
方法2:基于脚本目录构造路径(跨平台推荐)
利用k6内置的__DIR__变量获取当前脚本所在的绝对目录,结合path.join模块拼接路径,确保跨平台兼容性:
import { SharedArray } from 'k6/data'; import path from 'k6/path'; const data = new SharedArray('some name', function () { // 拼接相对于脚本目录的文件路径 const filePath = path.join(__DIR__, '../inputs/sample.json'); const f = JSON.parse(open(filePath)); return f; }); export default function () { const element = data[Math.floor(Math.random() * data.length)]; console.log(element); }
__DIR__会返回脚本文件所在的绝对路径,path.join会自动处理不同系统的路径分隔符(Windows用\,Linux/macOS用/),避免路径解析错误。
内容的提问来源于stack exchange,提问作者Abhi
相关产品推荐
相关产品推荐

