K6 Reading File Not Working

Hi

i have a small script that reads a file which is
export default function () {
try {
console.log(“Start”);
open(“./testfile.txt”);
console.log(“Finish”);

} catch (error) {
console.error(error);
return null;
}
}

when i run it, it doesn’t print “Finished” and the “console.error” prints on the console “ERRO[0000] {“value”:{}}”
keep in mind that the script and “testfile.txt” are both in the same location which is the desktop
and k6 version is: k6.exe v0.48.0 (commit/47c0a26798, go1.21.5, windows/amd64)
how can i solve this problem?

Hi @ibr112 welcome to the community forum!

It is because open() function is only available in init context.
running the script with e.g. v0.35.0 prints a correct error message:

ERRO[0000] The "open()" function is only available in the init stage (i.e. the global scope), see https://k6.io/docs/using-k6/test-life-cycle for more information  source=console

here is the documentation of the open() function

Rewrite the script like this, and it will work fine:

const filecontent = open("./testfile.txt");

export default function () {
  try {
    console.log("Start");
    console.log(filecontent);
    console.log("Finish");
  } catch (error) {
    console.error(error);
    return null;
  }
}

I hope this helps

1 Like

yes, it worked just fine thanks a lot
one question though, how did you get the full error message?
“ERRO[0000] The “open()” function is only available in the init stage (i.e. the global scope), see Test lifecycle for more information source=console”

on the console i couldn’t get any

1 Like

@ibr112

Running with an older k6 version (e.g. v0.35.0). So it seems something happened with this error message.

1 Like