Skip to main content
The qjs:std module provides wrappers to C standard library functions (stdlib.h and stdio.h) along with additional utilities for file operations, script evaluation, and environment management.
import * as std from 'qjs:std';

Process Control

exit(n)

Terminates the process with the specified exit code.
n
number
required
Exit code (0 for success, non-zero for error)
import * as std from 'qjs:std';

if (errorCondition) {
  std.exit(1);
}

gc()

Manually invokes the garbage collector cycle removal algorithm.
return
undefined
No return value
std.gc(); // Force garbage collection

Script Evaluation

evalScript(str, options)

Evaluates a string as JavaScript code in the global scope.
str
string
required
The JavaScript code to evaluate
options
object
Optional configuration object
backtrace_barrier
boolean
default:false
If true, error backtraces do not list stack frames below the evalScript call
async
boolean
default:false
If true, await is accepted in the script and a promise is returned
return
any
The result of the evaluated code, or a Promise if async is true
import * as std from 'qjs:std';

// Synchronous evaluation
const result = std.evalScript('2 + 2');
console.log(result); // 4

// Async evaluation
const promise = std.evalScript('await fetch(url)', { async: true });
const asyncResult = await promise.value;

loadScript(filename)

Loads and evaluates a JavaScript file in the global scope.
filename
string
required
Path to the JavaScript file to load
std.loadScript('config.js');

File Operations

loadFile(filename, options)

Loads a file and returns its contents.
filename
string
required
Path to the file to load
options
object
Optional configuration
binary
boolean
default:false
If true, returns a Uint8Array instead of a string
return
string | Uint8Array | null
File contents as a UTF-8 string or Uint8Array if binary mode. Returns null on I/O error.
import * as std from 'qjs:std';

// Load text file
const text = std.loadFile('data.txt');
if (text === null) {
  console.log('Failed to read file');
}

// Load binary file
const buffer = std.loadFile('image.png', { binary: true });

writeFile(filename, data)

Writes data to a file, creating it if it doesn’t exist.
filename
string
required
Path to the file to write
data
string | TypedArray | ArrayBuffer
Data to write. Strings are written in text mode (UTF-8), binary data in binary mode. undefined creates an empty file.
return
undefined
Throws an exception on error
// Write text
std.writeFile('output.txt', 'Hello World');

// Write binary data
const buffer = new Uint8Array([0x89, 0x50, 0x4E, 0x47]);
std.writeFile('data.bin', buffer);
On Windows, files are opened in text mode for strings and binary mode for typed arrays. This affects line ending conversion.

FILE Object

open(filename, flags, errorObj)

Opens a file using C’s fopen() function.
filename
string
required
Path to the file
flags
string
required
File mode: "r", "w", "a", "r+", "w+", "a+", with optional "b" for binary
errorObj
object
If provided, its errno property is set to the error code (0 on success)
return
FILE | null
FILE object or null on error
import * as std from 'qjs:std';

const err = {};
const f = std.open('data.txt', 'r', err);
if (!f) {
  console.log('Error:', std.strerror(err.errno));
} else {
  const content = f.readAsString();
  f.close();
}

popen(command, flags, errorObj)

Opens a process by creating a pipe (Unix/Linux/macOS only).
command
string
required
Command to execute
flags
string
required
Either "r" (read) or "w" (write)
errorObj
object
Optional error object
const f = std.popen('ls -l', 'r');
const output = f.readAsString();
f.close();
Not available on Windows and WASI platforms.

fdopen(fd, flags, errorObj)

Opens a file from a file descriptor.
fd
number
required
File descriptor
flags
string
required
File mode flags
import * as os from 'qjs:os';
import * as std from 'qjs:std';

const fd = os.open('file.txt', os.O_RDONLY);
const f = std.fdopen(fd, 'r');
const content = f.readAsString();
f.close();

tmpfile(errorObj)

Creates a temporary file that is automatically deleted when closed.
errorObj
object
Optional error object
return
FILE | null
FILE object or null on error
const temp = std.tmpfile();
temp.puts('temporary data');
temp.seek(0, std.SEEK_SET);
const data = temp.readAsString();
temp.close(); // File is automatically deleted

FILE Methods

All FILE objects have the following methods:

close()

Closes the file.
return
number
Returns 0 on success or -errno on error

puts(str)

Writes a string to the file with UTF-8 encoding.
str
string
required
String to write

printf(fmt, ...args)

Writes formatted output to the file.
fmt
string
required
Format string (C printf syntax)
...args
any
Values to format
f.printf('Value: %d, Name: %s\n', 42, 'test');

flush()

Flushes the file’s write buffer.

seek(offset, whence)

Seeks to a position in the file.
offset
number | BigInt
required
Byte offset
whence
number
required
std.SEEK_SET, std.SEEK_CUR, or std.SEEK_END
return
number
Returns 0 on success or -errno on error

tell()

Returns the current file position as a number.

tello()

Returns the current file position as a BigInt.

eof()

Returns true if at end of file.

fileno()

Returns the OS file handle (file descriptor).

error()

Returns true if an error occurred.

clearerr()

Clears the error indication.

read(buffer, position, length)

Reads bytes into an ArrayBuffer.
buffer
ArrayBuffer
required
Destination buffer
position
number
default:0
Byte position in buffer to start writing
length
number
default:"buffer.length"
Number of bytes to read
return
number
Number of bytes actually read

write(buffer, position, length)

Writes bytes from an ArrayBuffer or string.
buffer
ArrayBuffer | string
required
Source buffer or string
position
number
default:0
Byte position to start reading from
length
number
default:"buffer.length"
Number of bytes to write

getline()

Reads the next line from the file, excluding the newline character.
return
string | null
The line as a string, or null at EOF
while (true) {
  const line = f.getline();
  if (line === null) break;
  console.log(line);
}

readAsString(max_size)

Reads the file contents as a UTF-8 string.
max_size
number
Maximum bytes to read (reads entire file if omitted)

readAsArrayBuffer(max_size)

Reads the file contents as an ArrayBuffer.
max_size
number
Maximum bytes to read (reads entire file if omitted)

getByte()

Reads one byte.
return
number
The byte value (0-255) or -1 at EOF

putByte(c)

Writes one byte.
c
number
required
Byte value to write (0-255)

Standard Streams

std.in
FILE
Standard input
std.out
FILE
Standard output
std.err
FILE
Standard error
std.out.puts('Hello\n');
std.err.puts('Error message\n');

const line = std.in.getline();

Output Functions

puts(str)

Equivalent to std.out.puts(str).

printf(fmt, ...args)

Equivalent to std.out.printf(fmt, ...args).

sprintf(fmt, ...args)

Formats a string like C’s sprintf().
return
string
Formatted string
const msg = std.sprintf('Value: %d', 42);

Environment Variables

getenv(name)

Returns the value of an environment variable.
name
string
required
Environment variable name
return
string | undefined
Variable value or undefined if not set
const home = std.getenv('HOME');
const path = std.getenv('PATH');

setenv(name, value)

Sets an environment variable.
name
string
required
Variable name
value
string
required
Variable value
std.setenv('MY_VAR', 'my_value');

unsetenv(name)

Deletes an environment variable.
name
string
required
Variable name to delete
std.unsetenv('MY_VAR');

getenviron()

Returns all environment variables as an object.
return
object
Object with environment variable names as keys and values as strings
const env = std.getenviron();
console.log(env.PATH);
console.log(env.HOME);

Error Handling

std.Error

Enumeration object containing common error codes:
  • EINVAL - Invalid argument
  • EIO - I/O error
  • EACCES - Permission denied
  • EEXIST - File exists
  • ENOSPC - No space left
  • ENOSYS - Function not implemented
  • EBUSY - Device or resource busy
  • ENOENT - No such file or directory
  • EPERM - Operation not permitted
  • EPIPE - Broken pipe
if (errno === std.Error.ENOENT) {
  console.log('File not found');
}

strerror(errno)

Returns a human-readable error message.
errno
number
required
Error code
return
string
Error description
const err = {};
const f = std.open('missing.txt', 'r', err);
if (!f) {
  console.log(std.strerror(err.errno));
  // Output: No such file or directory
}

Seek Constants

  • std.SEEK_SET - Seek from beginning of file
  • std.SEEK_CUR - Seek from current position
  • std.SEEK_END - Seek from end of file

Network Utilities

urlGet(url, options)

Downloads a URL using the curl command (requires curl to be installed).
url
string
required
URL to download
options
object
Optional configuration
binary
boolean
default:false
If true, returns ArrayBuffer instead of string
full
boolean
default:false
If true, returns object with response, responseHeaders, and status
return
string | ArrayBuffer | object | null
Response data, or null on error. If full is true, returns object with response, responseHeaders, and status properties.
// Simple GET
const html = std.urlGet('https://example.com');

// Binary data
const data = std.urlGet('https://example.com/file.bin', { binary: true });

// Full response
const result = std.urlGet('https://api.example.com/data', { full: true });
if (result.response !== null) {
  console.log('Status:', result.status);
  console.log('Headers:', result.responseHeaders);
  console.log('Body:', result.response);
}
Not available on WASI. Requires curl to be installed on the system.

Build docs developers (and LLMs) love