grafana/k6 · error

open() can't be used with files that weren't previously…

Error message

open() can't be used with files that weren't previously opened during initialization (__VU==0), path: %q

What it means

readFile's deferred guard converts fsext.ErrPathNeverRequestedBefore: open() was called with a path that was NOT opened during initialization (__VU==0). k6 pre-loads all files in the init stage so VU isolation works; opening a new file mid-iteration (often due to path computed per-VU) is rejected.

Solutions

  1. Hoist all open() calls to the top level (init context) of the script
  2. Call open() unconditionally in init for every file a VU may need — not inside per-VU conditionals
  3. Use import.meta.resolve() for correct relative paths in ESM scripts
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at internal/js/initcontext.go:42 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18). Data as JSON: /api/errors/1d8d928ddb73426e. Report an issue: GitHub.

Appendix: source

Thrown at internal/js/initcontext.go:42

	filename = strings.TrimPrefix(filename, "file://")
	data, err := readFile(fs, fsext.Abs(basePWD.Path, filename))
	if err != nil {
		return nil, err
	}

	if len(args) > 0 && args[0] == "b" {
		ab := rt.NewArrayBuffer(data)
		return rt.ToValue(&ab), nil
	}
	return rt.ToValue(string(data)), nil
}

func readFile(fileSystem fsext.Fs, filename string) (data []byte, err error) {
	defer func() {
		if errors.Is(err, fsext.ErrPathNeverRequestedBefore) {
			// loading different files per VU is not supported, so all files should are going
			// to be used inside the scenario should be opened during the init step (without any conditions)
			err = fmt.Errorf(
				"open() can't be used with files that weren't previously opened during initialization (__VU==0), path: %q",
				filename,
			)
		}
	}()

	// Workaround for https://github.com/spf13/fsext/issues/201
	if isDir, err := fsext.IsDir(fileSystem, filename); err != nil {
		return nil, err
	} else if isDir {
		return nil, fmt.Errorf("open() can't be used with directories, path: %q", filename)
	}

	return fsext.ReadFile(fileSystem, filename)
}

// allowOnlyOpenedFiles enables seen only files
func allowOnlyOpenedFiles(fs fsext.Fs) {

View on GitHub (pinned to 01ffac6f24)