/ Docs

API Reference

Complete method signatures for all almostnode classes and functions.

createContainer()

createContainer(options?: ContainerOptions): { vfs, runtime, npm, serverBridge, execute, runFile, createREPL, on }

Creates a complete container environment with a virtual filesystem, runtime, package manager, and server bridge.

Options

PropertyTypeDescription
cwdstringWorking directory (default: '/')
envRecord<string, string>Environment variables for process.env
onConsole(level, ...args) => voidCallback for console output
baseUrlstringBase URL for the server bridge
onServerReady(port) => voidCalled when a server starts listening

Returns

PropertyTypeDescription
vfsVirtualFSVirtual filesystem instance
runtimeRuntimeCode execution runtime
npmPackageManagerPackage manager for installing npm packages
serverBridgeServerBridgeService worker bridge
execute(code) => resultShorthand for runtime.execute()
runFile(path) => resultShorthand for runtime.runFile()
createREPL() => { eval: (code) => unknown }Create an interactive REPL context
on(event, listener) => voidListen for events (e.g. 'server-ready')

VirtualFS

new VirtualFS()

In-memory POSIX-compatible filesystem.

File Operations

MethodSignatureDescription
writeFileSync(path: string, data: string | Uint8Array): voidWrite file (creates parent dirs)
readFileSync(path: string, encoding?: 'utf8'): string | Uint8ArrayRead file contents
existsSync(path: string): booleanCheck if path exists
statSync(path: string): StatsGet file metadata
unlinkSync(path: string): voidDelete a file
renameSync(oldPath: string, newPath: string): voidMove or rename a file
copyFileSync(src: string, dest: string): voidCopy a file
accessSync(path: string, mode?: number): voidCheck file access (throws if not found)
realpathSync(path: string): stringNormalize and resolve path

Directory Operations

MethodSignatureDescription
mkdirSync(path: string, options?: {recursive?: boolean}): voidCreate directory
readdirSync(path: string): string[]List directory contents
rmdirSync(path: string): voidRemove empty directory

Streams

MethodSignatureDescription
createReadStream(path: string): ReadStreamCreate readable stream
createWriteStream(path: string): WriteStreamCreate writable stream

Watching & Events

MethodSignatureDescription
watch(path: string, listener?: (event, filename) => void): FSWatcherWatch file or directory for changes
on(event: 'change' | 'delete', listener): thisListen for VFS changes globally
off(event: 'change' | 'delete', listener): thisRemove event listener

Serialization

MethodSignatureDescription
toSnapshot(): VFSSnapshotSerialize entire filesystem
VirtualFS.fromSnapshot(snapshot: VFSSnapshot): VirtualFSRestore from snapshot (static)

Runtime

new Runtime(vfs: VirtualFS, options?: RuntimeOptions)

Executes JavaScript and TypeScript with CommonJS module resolution and 40+ shimmed Node.js modules.

Constructor Options

PropertyTypeDescription
cwdstringWorking directory (default: '/')
envRecord<string, string>Environment variables
onConsole(level, ...args) => voidConsole output callback

Methods

MethodSignatureDescription
execute(code: string, filename?: string): {exports, module}Execute code string as a module
runFile(path: string): {exports, module}Execute a file from the VFS
executeAsync(code: string, filename?: string): Promise<result>Execute code asynchronously
runFileAsync(path: string): Promise<result>Execute a file asynchronously
createREPL(): { eval: (code: string) => unknown }Create a REPL context with persistent state
clearCache(): voidClear module cache (for HMR)
getVFS(): VirtualFSGet the VFS instance
getProcess(): ProcessGet the process shim

createREPL()

runtime.createREPL(): { eval: (code: string) => unknown }

Creates an interactive REPL context that evaluates expressions and persists variables between calls. Unlike execute() which returns module.exports, the REPL's eval() returns the value of the last expression.

const repl = runtime.createREPL();

// Expression values are returned directly
repl.eval('1 + 2');                      // 3
repl.eval("require('path').join('/a', 'b')"); // '/a/b'

// Variables persist across calls
repl.eval('const x = 42');
repl.eval('x * 2');                       // 84

// Full access to require, process, Buffer, console
repl.eval("const fs = require('fs')");
repl.eval("fs.writeFileSync('/test.txt', 'hello')");
repl.eval("fs.readFileSync('/test.txt', 'utf8')"); // 'hello'
Security

The REPL uses eval() internally to return expression values. While the eval runs in an isolated closure (not the global scope), it still has the same security boundary as execute(). For untrusted user input, always use a cross-origin sandboxed iframe — see the Security Guide. Running eval in the main window or a same-origin iframe allows the evaluated code to access cookies, localStorage, and the DOM of the host page.

Differences from execute()

Featureexecute()createREPL().eval()
Return valuemodule.exportsLast expression value
State persistenceFresh context each callVariables persist
const/letBlock-scoped (lost)Converted to var (persisted)
Use caseRun standalone scriptsInteractive shells, notebooks

createRuntime()

async createRuntime(vfs: VirtualFS, options?: CreateRuntimeOptions): Promise<IRuntime>

Creates a runtime with security isolation. Use this when you need sandboxed or worker-based execution.

Options

PropertyTypeDescription
sandboxstringURL for cross-origin sandbox iframe
dangerouslyAllowSameOriginbooleanAllow main-thread execution (no isolation)
useWorkerbooleanExecute in a Web Worker
Security

You must provide either a sandbox URL or set dangerouslyAllowSameOrigin: true. The sandbox option is recommended for untrusted code.

PackageManager

new PackageManager(vfs: VirtualFS, options?: { cwd?: string })

Installs npm packages into the virtual filesystem. Fetches from the npm registry, resolves dependencies, and extracts tarballs.

Methods

MethodSignatureDescription
install(packageSpec: string, options?: InstallOptions): Promise<InstallResult>Install a package (e.g. 'express', 'react@18')
installFromPackageJson(options?: InstallOptions): Promise<InstallResult>Install all dependencies from package.json
list(): Record<string, string>Get installed packages and versions

InstallOptions

PropertyTypeDescription
savebooleanSave to dependencies in package.json
saveDevbooleanSave to devDependencies
onProgress(info) => voidProgress callback

ServerBridge

getServerBridge(options?: BridgeOptions): ServerBridge

Get or create the global ServerBridge instance. Connects virtual servers to real browser URLs via a service worker.

Methods

MethodSignatureDescription
initServiceWorker(options?: { swUrl?: string }): Promise<void>Register and activate the service worker
registerServer(server, port: number, hostname?: string): voidRegister a virtual server on a port
unregisterServer(port: number): voidUnregister a server
getServerUrl(port: number): stringGet URL for the virtual server
getServerPorts(): number[]Get all registered port numbers
handleRequest(port, method, url, headers, body?): Promise<Response>Handle an incoming request directly

Events

ServerBridge extends EventEmitter and emits:

NextDevServer

new NextDevServer(vfs: VirtualFS)

A virtual Next.js dev server that supports both App Router and Pages Router, CSS Modules, API routes, dynamic routes, route groups, and HMR via React Refresh.

Import from almostnode/next.

ViteDevServer

new ViteDevServer(vfs: VirtualFS)

A virtual Vite dev server with React support, JSX/TSX transforms, npm module resolution, and HMR via React Refresh.

Import from almostnode/vite.

Utility Functions

resetServerBridge()

resetServerBridge(): void

Reset the global ServerBridge instance. Useful in tests to get a clean state.