API Reference
Complete method signatures for all almostnode classes and functions.
createContainer()
Creates a complete container environment with a virtual filesystem, runtime, package manager, and server bridge.
Options
| Property | Type | Description |
|---|---|---|
cwd | string | Working directory (default: '/') |
env | Record<string, string> | Environment variables for process.env |
onConsole | (level, ...args) => void | Callback for console output |
baseUrl | string | Base URL for the server bridge |
onServerReady | (port) => void | Called when a server starts listening |
Returns
| Property | Type | Description |
|---|---|---|
vfs | VirtualFS | Virtual filesystem instance |
runtime | Runtime | Code execution runtime |
npm | PackageManager | Package manager for installing npm packages |
serverBridge | ServerBridge | Service worker bridge |
execute | (code) => result | Shorthand for runtime.execute() |
runFile | (path) => result | Shorthand for runtime.runFile() |
createREPL | () => { eval: (code) => unknown } | Create an interactive REPL context |
on | (event, listener) => void | Listen for events (e.g. 'server-ready') |
VirtualFS
In-memory POSIX-compatible filesystem.
File Operations
| Method | Signature | Description |
|---|---|---|
writeFileSync | (path: string, data: string | Uint8Array): void | Write file (creates parent dirs) |
readFileSync | (path: string, encoding?: 'utf8'): string | Uint8Array | Read file contents |
existsSync | (path: string): boolean | Check if path exists |
statSync | (path: string): Stats | Get file metadata |
unlinkSync | (path: string): void | Delete a file |
renameSync | (oldPath: string, newPath: string): void | Move or rename a file |
copyFileSync | (src: string, dest: string): void | Copy a file |
accessSync | (path: string, mode?: number): void | Check file access (throws if not found) |
realpathSync | (path: string): string | Normalize and resolve path |
Directory Operations
| Method | Signature | Description |
|---|---|---|
mkdirSync | (path: string, options?: {recursive?: boolean}): void | Create directory |
readdirSync | (path: string): string[] | List directory contents |
rmdirSync | (path: string): void | Remove empty directory |
Streams
| Method | Signature | Description |
|---|---|---|
createReadStream | (path: string): ReadStream | Create readable stream |
createWriteStream | (path: string): WriteStream | Create writable stream |
Watching & Events
| Method | Signature | Description |
|---|---|---|
watch | (path: string, listener?: (event, filename) => void): FSWatcher | Watch file or directory for changes |
on | (event: 'change' | 'delete', listener): this | Listen for VFS changes globally |
off | (event: 'change' | 'delete', listener): this | Remove event listener |
Serialization
| Method | Signature | Description |
|---|---|---|
toSnapshot | (): VFSSnapshot | Serialize entire filesystem |
VirtualFS.fromSnapshot | (snapshot: VFSSnapshot): VirtualFS | Restore from snapshot (static) |
Runtime
Executes JavaScript and TypeScript with CommonJS module resolution and 40+ shimmed Node.js modules.
Constructor Options
| Property | Type | Description |
|---|---|---|
cwd | string | Working directory (default: '/') |
env | Record<string, string> | Environment variables |
onConsole | (level, ...args) => void | Console output callback |
Methods
| Method | Signature | Description |
|---|---|---|
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 | (): void | Clear module cache (for HMR) |
getVFS | (): VirtualFS | Get the VFS instance |
getProcess | (): Process | Get the process shim |
createREPL()
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'
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()
| Feature | execute() | createREPL().eval() |
|---|---|---|
| Return value | module.exports | Last expression value |
| State persistence | Fresh context each call | Variables persist |
const/let | Block-scoped (lost) | Converted to var (persisted) |
| Use case | Run standalone scripts | Interactive shells, notebooks |
createRuntime()
Creates a runtime with security isolation. Use this when you need sandboxed or worker-based execution.
Options
| Property | Type | Description |
|---|---|---|
sandbox | string | URL for cross-origin sandbox iframe |
dangerouslyAllowSameOrigin | boolean | Allow main-thread execution (no isolation) |
useWorker | boolean | Execute in a Web Worker |
You must provide either a sandbox URL or set dangerouslyAllowSameOrigin: true. The sandbox option is recommended for untrusted code.
PackageManager
Installs npm packages into the virtual filesystem. Fetches from the npm registry, resolves dependencies, and extracts tarballs.
Methods
| Method | Signature | Description |
|---|---|---|
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
| Property | Type | Description |
|---|---|---|
save | boolean | Save to dependencies in package.json |
saveDev | boolean | Save to devDependencies |
onProgress | (info) => void | Progress callback |
ServerBridge
Get or create the global ServerBridge instance. Connects virtual servers to real browser URLs via a service worker.
Methods
| Method | Signature | Description |
|---|---|---|
initServiceWorker | (options?: { swUrl?: string }): Promise<void> | Register and activate the service worker |
registerServer | (server, port: number, hostname?: string): void | Register a virtual server on a port |
unregisterServer | (port: number): void | Unregister a server |
getServerUrl | (port: number): string | Get 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:
'sw-ready'— service worker is active'server-ready'— a server started listening'server-registered'— server registered on a port'server-unregistered'— server removed from a port
NextDevServer
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
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()
Reset the global ServerBridge instance. Useful in tests to get a clean state.