💾 Archived View for zvava.org › wiki › qjs.gmi captured on 2024-02-05 at 09:37:54. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-11-04)
-=-=-=-=-=-=-
created 2023/06/01 modified 2023/10/18 category info, software
quickjs is a small and embeddable javascript engine by the same guy who wrote tcc (tiny cc (c compiler)). it supports the ES2020 specification and is complete with all modern javascript features, and a hearty standard library which includes i/o and concurrency api!
also comes with qjsc, a compiler that can compile any qjs script to an executable or its equivalent c code
import * as std from "std" import * as os from "os"
additions to the global scope:
scriptArgs
provides the command line arguments. The first argument is the script name
print(...args)
print the arguments separated by spaces and a trailing newline
same as console.log()
wrappers to the libc stdlib.h and stdio.h, and a few other utilities;
exit(n)
exit the process.
evalScript(str, options = undefined)
evaluate the string str as a script (global eval)
options is an optional object containing `backtrace_barrier`, if true, error backtraces do not list the stack frames below the evalScript
loadScript(filename)
evaluate the file filename as a script (global eval)
loadFile(filename)
load the file filename and return it as a string assuming UTF-8 encoding. return null in case of I/O error
open(filename, flags, errorObj = undefined)
open a file (wrapper to the libc fopen()). return the FILE object or null in case of I/O error
puts(str)
equivalent to std.out.puts(str)
printf(fmt, ...args)
equivalent to std.out.printf(fmt, ...args)
sprintf(fmt, ...args)
equivalent to the libc sprintf()
in, out, & err
wrappers to the libc file stdin, stdout, stderr
gc()
manually invoke the cycle removal algorithm. the cycle removal algorithm is automatically started when needed, this is useful for specific memory constraints
getenv(name)
return the value of the environment variable name or undefined if it is not defined
setenv(name, value)
set the value of the environment variable name to the string value
unsetenv(name)
delete the environment variable name
getenviron()
return an object containing the environment variables as key-value pairs
urlGet(url, options = undefined)
download url using the curl command line utility. options is an optional object containing the following optional properties:
- binary
if true, the response is an ArrayBuffer instead of a string. when a string is returned, the data is assumed to be UTF-8 encoded
- full
if true, return the an object contains the properties response (response content), responseHeaders (headers separated by CRLF), status (status code). response is null is case of protocol or network error
by default, the response is only returned if the status is 2XX, otherwise null is returned
parseExtJSON(str)
superset of JSON.parse, allowing for trailing commas, comments, hex/octal numbers, and a few other niceties
the os module provides operating system specific functions like signals, timers, async i/o, and concurrency; these functions usually return 0 if ok, or an os specific negative error code;
platform
return a string representing the platform: "linux", "darwin", "win32" or "js"
sleep(delay)
pause execution for delay milliseconds
setTimeout(func, delay)
call the function func after delay milliseconds. return a handle to the timer
clearTimeout(handle)
cancel a timer
exec(args[, options])
execute a process with args being an array. options is an object containing optional parameters:
- block
true by default, wait until the process is terminated and return the exit status. if false, do not block and return the process id of the child
- usePath
true by default, the file is searched in the PATH environment variable
- cwd
if present, set the working directory of the new process
- stdin, stdout, & stderr
if present, set the handle in the child for stdin, stdout or stderr.
- env
if present, set the process environment from the object key-value pairs. otherwise use the same environment as the current process
isatty(fd)
return true is fd is a TTY (terminal emulator) handle
ttyGetWinSize(fd)
return the TTY size as [width, height] or null if not available
ttySetRaw(fd)
set the TTY to raw mode
remove(filename)
remove a file
rename(oldname, newname)
rename a file
realpath(path)
return [str, err] where str is the canonicalized absolute pathname of path
getcwd()
return [str, err] where str is the current working directory
chdir(path)
change the current directory
mkdir(path, mode = 0o777)
create a directory at path
readdir(path)
return [arr, err] where arr is an array of strings containing the filenames of the directory path
stat(path)
lstat(path)
return [obj, err] where obj is an object containing the file status of path
the following fields are defined in obj: dev, ino, mode, nlink, uid, gid, rdev, size, blocks, atime, mtime, ctime
the times are specified in milliseconds since 1970. lstat() is the same but returns information about the link itself
utimes(path, atime, mtime)
change the access and modification times of the file path. the times are specified in milliseconds since 1970
symlink(target, linkpath)
create a link at linkpath containing the string target
readlink(path)
return [str, err] where str is the link target
you can create threads, interchangeably called workers, with an API close to WebWorkers. threads normally don’t share any data and communicate between each other with messages. nested workers are not supported
- Worker(module_filename)
constructor to create a new worker. module_filename is a string specifying the module filename relative to the current script or module path. it has the static property parent
- Worker.parent
in the created worker, Worker.parent represents the parent worker and is used to send or receive messages.
the worker instances have the following properties:
- postMessage(msg)
send a message to the corresponding worker. msg is cloned in the destination worker using an algorithm similar to the html-structured clone algorithm. SharedArrayBuffer are shared between workers
- onmessage
setter/getter to an event handler, is called with a single argument each time a message is received. that argument is an object with a data property containing the received message
the thread is not terminated if there is at least one non-null onmessage handler
close()
close the file
puts(str)
outputs the string with the UTF-8 encoding
printf(fmt, ...args)
formatted printf
flush()
flush the buffered file
seek(offset, whence)
seek to a give file position, whence is std.SEEK_*
tell() & tello()
return the current file position. tello does the same but with bigint
eof()
return true if end of file has been reached
error()
return true if there was an error
read(buffer, position, length) & write(buffer, position, length)
read/write length bytes from the file to the ArrayBuffer buffer at byte position position (wrapper to the libc fread/fwrite)
getline()
return the next line from the file, assuming UTF-8 encoding, excluding the trailing line feed.
readAsString(max_size = undefined)
read max_size bytes from the file and return them as a string assuming UTF-8 encoding. if max_size is not present, the file is read up its end
getByte()
return the next byte from the file. returns -1 when eof is reached
putByte(c)
write one byte to the file