Node.js
Add Node.js runtime to your VMs.
The Node.js integration installs Node.js via NVM and provides helper methods for running JavaScript code and installing packages.
Installation
npm install @freestyle-sh/with-nodejs freestyle-sandboxesUsage
import { freestyle } from "freestyle-sandboxes";
import { VmNodeJs } from "@freestyle-sh/with-nodejs";
const { vm } = await freestyle.vms.create({
with: {
node: new VmNodeJs(),
},
});
const res = await vm.node.runCode({
code: "console.log(JSON.stringify({ hello: 'world' }));"
});
console.log(res);
// { result: { hello: 'world' }, stdout: '{"hello":"world"}\n', statusCode: 0 }Options
new VmNodeJs({
version: "22", // Optional: Node.js version (default: "24")
})| Option | Type | Default | Description |
|---|---|---|---|
version | string | "24" | Node.js version to install via NVM |
API
vm.node.runCode({ code })
Executes JavaScript code in the Node.js runtime.
const res = await vm.node.runCode({
code: `
const data = { sum: 1 + 2, timestamp: Date.now() };
console.log(JSON.stringify(data));
`
});
console.log(res.result); // { sum: 3, timestamp: 1234567890 }Returns: Promise<RunCodeResponse>
type RunCodeResponse<Result> = {
result: Result; // Parsed JSON from stdout (if valid JSON)
stdout?: string; // Raw stdout output
stderr?: string; // Raw stderr output
statusCode?: number; // Exit code
};vm.node.install(options?)
Installs npm packages.
// Install from package.json in current directory
await vm.node.install();
// Install from package.json in specific directory
await vm.node.install({ directory: "/app" });
// Install specific packages
await vm.node.install({ deps: ["lodash", "express"] });
// Install with specific versions
await vm.node.install({ deps: { "lodash": "^4.0.0", "express": "~5.0.0" } });
// Install as dev dependencies
await vm.node.install({ deps: ["typescript"], dev: true });
// Install globally
await vm.node.install({ global: true, deps: ["typescript"] });Returns: Promise<InstallResult>
type InstallResult = {
success: boolean;
stdout?: string;
stderr?: string;
};Example: Run Code and Get Result
import { freestyle } from "freestyle-sandboxes";
import { VmNodeJs } from "@freestyle-sh/with-nodejs";
const { vm } = await freestyle.vms.create({
with: {
node: new VmNodeJs({ version: "22" }),
},
});
// Run code that outputs JSON
const res = await vm.node.runCode({
code: `
const result = Array.from({ length: 5 }, (_, i) => i * 2);
console.log(JSON.stringify(result));
`
});
console.log(res.result); // [0, 2, 4, 6, 8]