Study · Node.js + TypeScript · exact npm 2.3.2
Natural ESM handlers, one shared native HTTP runtime
Node.js keeps its familiar event loop, Promises and TypeScript declarations. CoAkka HTTP Runtime keeps transport, bounds, route truth and finite lifecycle.
Beginner · 01 / 04
Install the package made for Node.js
mkdir coakka-http-node-study
cd coakka-http-node-study
npm init -y
npm install --save-exact [email protected]- Node.js
- 22+; inspect it with
node --versionandnode -p process.arch. - Package
[email protected]; do not substitute the Bun package even though the declaration surfaces match.- Native payload
- The tarball bundles all five targets; the loader selects from the Node process OS and CPU.
- ESM
- The package has
type: module. Study uses.mjsto make intent explicit without editing package metadata. - TypeScript
index.d.tsships in the package; use the same imports and camelCase contract, not another wrapper API.
Beginner · 02 / 04
Run one complete ESM service
Save the complete file below as server.mjs:
import { Builder, Response } from "coakka-http-runtime-node";
const service = new Builder()
.listen("127.0.0.1", 0)
.get("/hello/{name}", (request) => {
const encodedName = request.pathParameters[0].encodedValue;
const name = Buffer.from(encodedName).toString("utf8");
return Response.text(`hello ${name}`, { status: 200 });
})
.start();
console.log(`http://127.0.0.1:${service.port}/hello/Ada`);
console.log("Press Ctrl+C to close");
process.once("SIGINT", () => {
service.close().catch((error) => {
console.error("CoAkka HTTP Runtime close failed", error);
process.exitCode = 1;
});
});
node server.mjsOpen the printed URL, or run curl -i http://127.0.0.1:49321/hello/Ada. Expect 200 hello Ada. Ctrl+C invokes and observes the Promise returned by service.close().
127.0.0.1- Study listens on loopback only.
0- The OS selects a port; read
service.portafter start. - Signal handler
- Do not call
process.exit()before close settles; a close error leaves a non-zero exit code.
Beginner · 03 / 04
The request is a JavaScript-owned copy
const encodedName = request.pathParameters[0].encodedValue;
const name = Buffer.from(encodedName).toString("utf8");
return Response.text(`hello ${name}`, { status: 200 });
pathParameters- Ordered captures;
encodedValueholds percent-encoded bytes. queryParameters- Preserves order, duplicates and null-versus-empty.
headers.getAll()- Header names are case-insensitive and duplicate values remain available.
request.bytes()- Returns a defensive body copy within the configured bound; large uploads use
postStream. Response.text- The options object makes status and headers explicit; JSON and domain codecs remain app-owned.
Ordinary request values have been copied away from native memory. That does not make an application array or cache safe to grow without bounds.
Beginner · 04 / 04
Await the outbound terminal, then await close
Keep the server running and save this file as outbound.mjs:
import {
Builder,
OutboundReason,
TransportSecurity,
} from "coakka-http-runtime-node";
const port = Number.parseInt(process.argv[2] ?? "", 10);
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
throw new TypeError("Pass the server port as the first argument");
}
const service = new Builder()
.outboundTarget({
name: "hello",
generation: 1,
endpoints: [{
nodeId: "loopback",
connectHost: "127.0.0.1",
connectPort: port,
httpAuthority: `127.0.0.1:${port}`,
security: TransportSecurity.PLAINTEXT,
}],
})
.start();
try {
const call = service.outboundSubmit({
logicalTarget: "hello",
method: "GET",
target: "/hello/Ada",
timeoutMillis: 3_000,
});
const terminal = await service.takeOutbound(5_000);
if (terminal === null) {
throw new Error("No outbound terminal within five seconds");
}
if (
terminal.call.slot !== call.slot
|| terminal.call.generation !== call.generation
) {
throw new Error("Outbound terminal belongs to another call");
}
if (terminal.reason !== OutboundReason.RESPONSE) {
throw new Error(`Outbound ended with reason ${terminal.reason}`);
}
console.log(
terminal.responseStatus,
new TextDecoder().decode(terminal.body),
);
} finally {
await service.close();
}
SERVER_PORT=49321
node outbound.mjs "$SERVER_PORT"Replace 49321 with the real port. Expect 200 hello Ada. Match both slot and generation; terminal reason is separate from HTTP status, and the Promise reader does not block the event loop.
Advanced · 05
Learn one capability at a time, then combine them
Each first file opens one endpoint with the Node 2.3.2 package.
01 · File deliveryAuthority, path and limits; the Runtime selects sendfile when eligible.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Builder, FileResponse } from "coakka-http-runtime-node";
const root = mkdtempSync(join(tmpdir(), "coakka-http-file-"));
writeFileSync(join(root, "manual.txt"), "CoAkka file delivery\n");
const service = new Builder()
.listen("127.0.0.1", 0)
.fileAuthority({
id: 1,
rootPath: root,
maxActiveFiles: 4,
maxFileBytes: 1024,
})
.get("/download", () => new FileResponse(1, "/manual.txt"), { response: "file" })
.start();
console.log(`curl http://127.0.0.1:${service.port}/download`);
process.once("SIGINT", async () => {
try {
await service.close();
} finally {
rmSync(root, { recursive: true, force: true });
}
});
node file.mjs02 · Server-Sent EventsTwo one-way events and an explicit terminal.
import { Builder, sse } from "coakka-http-runtime-node";
const service = new Builder()
.listen("127.0.0.1", 0)
.get("/events", () => sse([
{ data: "ready", event: "state", id: "1", retry: 1000n },
{ data: "done" },
]), { response: "sse" })
.start();
console.log(`curl -N http://127.0.0.1:${service.port}/events`);
process.once("SIGINT", async () => {
await service.close();
});
node sse.mjs03 · WebSocketSubprotocol, greeting and bidirectional text echo.
import { Builder, websocket } from "coakka-http-runtime-node";
const service = new Builder()
.listen("127.0.0.1", 0)
.get("/socket", () => websocket({
protocol: "coakka.demo",
open(session) {
session.send("ready");
},
message(session, message) {
if (message.type === "text") session.send(`echo: ${message.data}`);
},
}), { response: "websocket" })
.start();
console.log(
`new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')`,
);
process.once("SIGINT", async () => {
await service.close();
});
node websocket.mjs04 · Combine them in one serviceAn optional integration exercise after the three contracts are clear.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
Builder,
FileResponse,
sse,
websocket,
} from "coakka-http-runtime-node";
const root = mkdtempSync(join(tmpdir(), "coakka-http-advanced-"));
writeFileSync(join(root, "manual.txt"), "CoAkka file delivery\n");
const service = new Builder()
.listen("127.0.0.1", 0)
.fileAuthority({
id: 1,
rootPath: root,
maxActiveFiles: 4,
maxFileBytes: 1024,
})
.get("/download", () => new FileResponse(1, "/manual.txt"), { response: "file" })
.get("/events", () => sse([
{ data: "ready", event: "state", id: "1", retry: 1000n },
{ data: "done" },
]), { response: "sse" })
.get("/socket", () => websocket({
protocol: "coakka.demo",
open(session) {
session.send("ready");
},
message(session, message) {
if (message.type === "text") session.send(`echo: ${message.data}`);
},
}), { response: "websocket" })
.start();
console.log(`file: curl http://127.0.0.1:${service.port}/download`);
console.log(`SSE: curl -N http://127.0.0.1:${service.port}/events`);
console.log(`WS: new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')`);
let closing = false;
async function close() {
if (closing) return;
closing = true;
try {
await service.close();
} finally {
rmSync(root, { recursive: true, force: true });
}
}
process.once("SIGINT", () => {
close().catch((error) => {
console.error("CoAkka HTTP Runtime close failed", error);
process.exitCode = 1;
});
});
node advanced.mjsUse Ctrl+C to close the service. Look up parameters, failure modes and monitoring.
Find all feature guides · Try gzip · Run the upload labs · Resume a large upload · Try V1 handler replacement
Advanced · 06
Live routes use Core-issued revisions
| Operation | Node.js API | Invariant |
|---|---|---|
| Snapshot | service.routes / routeSnapshot() | A coherent Core cut, not local declarations. |
| Prepare | prepareHandler | Prepare an immutable binding before activation. |
| Rebind | rebindHandler | Expected generation/revision; admitted requests keep the old binding. |
| Publish | publishRoutes | One complete structural generation. |
| TLS | tlsReload | Read a typed applied/rejected outcome. |
Advanced · 07
Effective state, Monitor and the Electron boundary
runtimeInfo()- Core-issued requested, probed and effective provider facts.
health()/probeLiveness()- Direct health and a fresh bounded probe do not require Monitor.
- Monitor
- Reserve with
Builder.monitor(), then pullmonitorConfig/Snapshot/Read; a signal is only a hint. pollError()- Bounded handler and producer diagnostics; never a second response.
- Electron
- The main process retains exactly one service owner and awaits close; renderer and preload never retain native objects. The app still owns IPC schema and renderer trust.
Advanced · 08
Failure, awaited close and Node.js quick reference
- Startup/import
- Inspect package identity, Node process OS/architecture and bundled native path; unsupported targets fail early.
- Handler/producer
- Await async work; errors enter the bounded diagnostic queue; never busy-poll the event loop.
- Outbound
- Match call identity, reason, phase/retry/certainty; never infer retry from status or text.
- Close
close()returns a Promise. Refused or failed drain retains the owner for retry; never fire-and-forget and exit.- Evidence
- Tarball/hash, Node path/version/architecture, loaded JS/native paths, runtime info, health and terminal/loss facts.
- Node.js 22+ and the exact Node package 2.3.2.
- Do not substitute the Bun package as an alias.
- Await writers, terminal readers and close.
- Stream
disposeremoves bounded state exactly once. - Keep Electron's native owner in the main process only.