Global context for initialization code and environment access
The init context (also called “init code”) is code in the global context that runs before the test starts. It has access to special functions and variables not available during main script execution.
File contents as string or ArrayBuffer (if binary mode)
open() can only be called from the init context. This restriction allows k6 to determine which local files to bundle when distributing tests across multiple nodes.
Current iteration number for the VU. Starts at 0 and increments with each iteration.Example:
console.log(`Iteration ${__ITER}`);
For more comprehensive execution context information, use the k6/execution module which provides detailed metadata about scenarios, instances, and test state.
import { SharedArray } from 'k6/data';import { sleep } from 'k6';const data = new SharedArray('users', function () { // open() is called in init context const f = JSON.parse(open('./users.json')); return f; // f must be an array});export default () => { const randomUser = data[Math.floor(Math.random() * data.length)]; console.log(`${randomUser.username}, ${randomUser.password}`); sleep(3);};
import http from 'k6/http';import { sleep } from 'k6';const binFile = open('/path/to/file.bin', 'b');export default function () { const data = { field: 'this is a standard form field', file: http.file(binFile, 'test.bin'), }; const res = http.post('https://example.com/upload', data); sleep(3);}
import { SharedArray } from 'k6/data';import http from 'k6/http';const users = new SharedArray('users', () => { return JSON.parse(open('./users.json'));});export default function () { // Each VU gets a specific user const user = users[__VU - 1]; const res = http.post('https://test.k6.io/login', { username: user.username, password: user.password, }); console.log(`VU ${__VU} logged in as ${user.username}`);}
import { SharedArray } from 'k6/data';// Good: Memory is shared between all VUsconst data = new SharedArray('my-data', () => { return JSON.parse(open('./large-file.json'));});