How to check a file exists with K6

I have a scenario where I want to check the test data file exists for the test program before executing the test. I tried using fs base module using import fs from “fs” but it did not work.

is there any other way that I can verify the existence of the test data file with in the k6 file (.js file)?

Hi @sashi1

In k6 you can use the built-in open() function to check the existence of a file. Since k6 doesn’t support the full NodeJS API, the fs module won’t work directly.

To verify the existence of a file within a k6 script, you can use the open() function and handle any errors that occur if the file doesn’t exist. Here’s an example of how you can achieve this:

import { open } from 'k6';

export default function () {
  const filePath = 'path/to/testdata.json';

  try {
    const file = open(filePath);
    console.log(`File '${filePath}' exists.`);
  } catch (error) {
    console.log(`File '${filePath}' does not exist.`);

  // Rest of your test script

Running the above script:

If you plan to use a SharedArray, which is probably best for shared test data (better performance), the script errors if the test tries to open a file that does not exist:

ERRO[0000] GoError: stat somefile.json: no such file or directory
        at*Bundle).setInitGlobals.func2 (native)
        at file:///Users/immavalls/Documents/imma/github/k6-community/community-support/working-topics/2023-05/scripts/file-exists-sharedarray.js:6:30(5)
        at file:///Users/immavalls/Documents/imma/github/k6-community/community-support/working-topics/2023-05/scripts/file-exists-sharedarray.js:3:13(21)  hint="script exception"

Would that work for you, simply fail when the file does not exist?

You might also be able to verify if the file exists using the xk6-exec extension, similar to Delete a file using xk6-file - #5 by javaducky_1 - Extensions - Grafana Labs Community Forums for a delete.

Depending on your needs and requirements, there are several options.

I hope this helps.


Thank you. I used the open() to verify the existence. Could there be a memory issue using open() ?

as mentioned in JavaScript API: open

Hi @sashi1

Indeed if the file is big it can cause memory issues, and that’s why we recommend Shared Array. Which is usually used not to check if a file exists, though, but to make the contents available to the virtual users.