Overview
Before k6 starts the test logic, code in the init context prepares the script by:- Importing modules
- Loading files
- Defining global variables
- Setting up configuration
- Initializing shared resources
For details about the runtime and execution phases, refer to the Test Lifecycle documentation.
Init Context Functions
open()
function
Opens a file and reads all its contents into memory for use in the script.Parameters:Returns:
string
required
Path to the file (absolute or relative). The file is loaded once even when running with multiple VUs.
string
File read mode:
- Omit or
"t"- Read as text (default) "b"- Read as binary data (ArrayBuffer)
string | ArrayBuffer
File contents as string or ArrayBuffer (if binary mode)
Global Variables
These variables are available throughout your script:Environment Variables
object
Object containing environment variables as key-value pairs. Access environment variables passed to k6 via
-e or --env flags.Example:VU Information
number
Current VU (Virtual User) number. Starts at 1 and increments for each VU.Example:
number
Current iteration number for the VU. Starts at 0 and increments with each iteration.Example:
For more comprehensive execution context information, use the
k6/execution module which provides detailed metadata about scenarios, instances, and test state.Examples
Loading JSON Data
Loading Binary Files
Using Environment Variables
Per-VU Data Assignment
Conditional Configuration
Memory Efficiency with SharedArray
To reduce memory consumption:Use SharedArray
Use k6/experimental/fs
Init Context vs Default Function
Code Example
Best Practices
Minimize Init Context Work
Minimize Init Context Work
Keep init context code minimal and fast. Heavy operations in init context delay test startup and increase memory usage per VU.
Validate Environment Variables
Validate Environment Variables
Provide defaults for environment variables and validate required ones in init context.
Use __VU and __ITER Appropriately
Use __VU and __ITER Appropriately
Use
__VU for per-VU data distribution and __ITER for iteration-specific logic.Related Resources
k6/execution
Detailed execution context and metadata
SharedArray
Share data efficiently between VUs
k6/experimental/fs
Memory-efficient file operations
Test Lifecycle
Understanding k6 execution phases