Browse packages

Package · v0.27.0 · changelog

runtime

Standard library runtime environment

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

Browser: Detection and flags work; process and project operations throw.

This module identifies the current JavaScript environment and provides its executable path, current script, arguments, memory usage, and process controls. It uses runtime keys for accurate detection without any runtime overhead.

Installation#

bash
npm install @rcompat/runtime
bash
pnpm add @rcompat/runtime
bash
yarn add @rcompat/runtime
bash
bun add @rcompat/runtime

Usage#

Basic detection#

js
import runtime from "@rcompat/runtime";

console.log(runtime.name);
// "node" | "bun" | "deno" | "browser"

Conditional logic#

js
import runtime from "@rcompat/runtime";

if (runtime.name === "bun") {
  // Bun-specific code
} else if (runtime.name === "deno") {
  // Deno-specific code
} else if (runtime.name === "node") {
  // Node.js-specific code
}

Executable path#

js
import runtime from "@rcompat/runtime";

console.log(runtime.bin);
// "/usr/local/bin/node"
// "/home/user/.bun/bin/bun"
// "/usr/bin/deno"

Current script#

js
import runtime from "@rcompat/runtime";

console.log(runtime.script);
// "/path/to/your/script.js"

Program arguments#

js
import runtime from "@rcompat/runtime";

// running: node app.js foo bar
console.log(runtime.args);
// ["foo", "bar"]

runtime.args always contains only your program's arguments — the runtime executable and script path are stripped away, consistently across all runtimes.

Program flags#

Use runtime.flags.get(key, fallback) to read a flag. A stored value takes precedence, including an empty string for a flag passed without a value. If the flag is missing, get returns the fallback and throws when it is omitted or undefined. Use runtime.flags.has(key) to check whether a flag was passed.

js
import runtime from "@rcompat/runtime";

const output = runtime.flags.get("--outdir", "dist");
const verbose = runtime.flags.has("--verbose");

Exiting the process#

js
import runtime from "@rcompat/runtime";

runtime.exit(0);  // success
runtime.exit(1);  // failure

In browsers, process operations such as exit, cwd, and resolve throw an unimplemented error.

Current-process lifecycle#

On POSIX Node, Bun, and Deno, runtime.on.interrupt(callback), runtime.on.terminate(callback), and runtime.on.hangup(callback) subscribe to SIGINT, SIGTERM, and SIGHUP respectively. Each registration returns its own idempotent unsubscribe function, including when the same callback is registered twice. Subscriptions remain active until removed; callbacks run on each delivery. runtime.interrupt(), runtime.terminate(), and runtime.hangup() send the corresponding signal to this process without removing any listeners. All intercepting listeners (including listeners installed outside rcompat) must be removed before a re-signal can restore default termination. A signal listener alone does not keep the process alive.

js
import runtime from "@rcompat/runtime";

const timeout = ms => new Promise((_, reject) => {
  setTimeout(() => reject(new Error("shutdown timed out")), ms);
});

const unsubscribe = runtime.on.terminate(() => {
  void (async () => {
    try {
      await Promise.race([closeResources(), timeout(2000)]);
    } catch (error) {
      console.error("cleanup failed", error);
    } finally {
      unsubscribe();
      runtime.terminate();
    }
  })();
});

The application supplies closeResources and handles cleanup errors according to its policy. Use finally to remove its listener and re-signal even if cleanup rejects or times out. Re-signalling does not override other signal listeners.

runtime.before.exit(callback) registers one callback for natural event-loop exhaustion. It removes itself before calling the callback, so scheduled asynchronous cleanup can finish without invoking the callback again. The subscription keeps the event loop alive until the callback's returned promise settles, even if its work has no referenced I/O or timer of its own. The returned unsubscribe is idempotent. Consumers must still bound cleanup: a promise that never settles keeps the process alive indefinitely. The callback is not invoked after runtime.exit(), forced exits, crashes, or SIGKILL. The runtime does not swallow callback exceptions or rejected promises; the consumer must handle errors and bound cleanup itself.

These lifecycle operations throw unimplemented when called in browsers. Windows signal behavior is not supported by this contract.

Module resolution#

js
const filename = runtime.resolve("example", "/path/to/project");

runtime.resolve() resolves relative and absolute paths directly. For bare package specifiers, it finds the owning node_modules package and applies ESM exports or imports using the running host's import conditions. Resolution preserves nested package ownership, package self references, subpath patterns, and legacy main packages. It returns a filesystem path; built-in node: specifiers remain unchanged.

This is import resolution, not require.resolve(). Use runtime.toRequire() when CommonJS resolution is specifically required. Browsers do not have an npm package filesystem and throw unimplemented when resolve() is called.

Node resolution observes startup conditions from command-line options and NODE_OPTIONS. Bun uses its native resolver first. Deno resolution observes its built-in conditions and readable DENO_CONDITIONS; Deno does not expose CLI --conditions after startup or reveal when those values override the environment, so runtime.resolve() cannot reproduce hidden CLI conditions.

Process memory usage#

js
const usage = runtime.memoryUsage();

if (usage) {
  console.log(usage.rss);
  console.log(usage.heapUsed);
}

runtime.memoryUsage() returns an instantaneous aggregate process-memory sample. Every available value is measured in bytes. It does not trigger garbage collection, enable an inspector or profiler, retain sample history, or start background sampling.

Node and Bun provide all fields. Deno does not expose arrayBuffers through its native aggregate API, so that field is undefined. Browsers return undefined because there is no portable browser API with equivalent process memory categories. In particular, this package does not use the non-standard Chromium-only performance.memory API.

Supported Runtimes#

Runtime Value
Node.js "node"
Bun "bun"
Deno "deno"
Browser "browser"

How It Works#

This package uses runtime keys, a WinterCG proposal for runtime detection. The exports field in package.json routes to different files based on the runtime condition, meaning detection happens at import time with zero runtime overhead.

json
{
  "exports": {
    ".": {
      "bun": "./lib/public/bun.js",
      "deno": "./lib/public/deno.js",
      "browser": "./lib/public/browser.js",
      "node": "./lib/public/node.js"
    }
  }
}

Each file simply exports the runtime object for that environment:

ts
// node.ts
export default {
  name: "node",
  bin: process.execPath,
  script: process.argv[1],
  args: process.argv.slice(2),
  exit: (code?: number) => process.exit(code),
};

Examples#

Relaunching with custom flags#

js
import runtime from "@rcompat/runtime";
import io from "@rcompat/io";

// relaunch self with --conditions=source
const child = io.spawn(runtime.bin, [
  "--conditions=@rcompat/source",
  runtime.script,
  ...runtime.args,
], { stdio: "inherit" });

const status = await child.status;
runtime.exit(status.code ?? 1);

Runtime-specific logging#

js
import runtime from "@rcompat/runtime";

const logger = {
  info(message) {
    console.log(`[${runtime.name}]`, message);
  }
};

logger.info("Server started");
// [node] Server started
// [bun] Server started

Environment checks#

js
import runtime from "@rcompat/runtime";

const isServerRuntime = ["node", "bun", "deno"].includes(runtime.name);
const isClientRuntime = runtime.name === "browser";

Debug information#

js
import runtime from "@rcompat/runtime";

function getDebugInfo() {
  return {
    runtime: runtime.name,
    script: runtime.script,
    args: runtime.args,
    timestamp: Date.now(),
  };
}

Reading active conditions#

ts
import runtime from "@rcompat/runtime";

const conditions = await runtime.conditions();

Cross-Runtime Compatibility#

Runtime Supported
Node.js ✓
Bun ✓
Deno ✓
Browser Limited

Browser detection and argument flags work. Process, filesystem-project, and module-resolution operations are unavailable, and process memory usage returns undefined.

License#

MIT

Contributing#

See CONTRIBUTING.md in the repository root.