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.

3 Likes

I tried the examples in the documentation and also with the above script, but still facing the issues.
Here is the exception which I got
getting this error
ERRO[0000] TypeError: Value is not an object: undefined

I tried all the possibilities. Please help me on this.

I am using the K6 version (k6.exe v0.52.0 (commit/20f8febb5b, go1.22.4, windows/amd64))

It worked when i removed

  1. import {open} from ‘k6’;
    and
  2. Placed the open() function before the export default function(){}

Thanks.