Browser-based code execution environment for Node.js with TypeScript support and React bindings.
- Run Node.js code directly in the browser without a server
- Full Node.js runtime powered by StackBlitz WebContainer
- TypeScript support with type definitions
- React integration with hooks and providers
- Virtual file system for file operations
- Singleton pattern for efficient resource usage
- Install and use npm packages
npm install @examples-ai/code-container
# or
yarn add @examples-ai/code-container
# or
pnpm add @examples-ai/code-container
import { NodeContainer } from '@examples-ai/code-container';
// Initialize the container
const container = await NodeContainer.boot();
// Execute Node.js code
const result = await container.run(`
console.log('Hello from Node.js!');
const fs = require('fs');
fs.writeFileSync('/tmp/test.txt', 'Hello World');
const content = fs.readFileSync('/tmp/test.txt', 'utf8');
console.log('File content:', content);
content
`);
console.log(result); // Output from Node.js
npm install @examples-ai/code-container react react-dom swr
import { useState } from 'react';
import {
NodeContainerProvider,
useNodeContainer,
} from '@examples-ai/code-container';
function App() {
return (
<NodeContainerProvider>
<NodeEditor />
</NodeContainerProvider>
);
}
function NodeEditor() {
const { webContainer, isLoading, error } = useNodeContainer();
const [output, setOutput] = useState('');
const runCode = async (code: string) => {
if (!webContainer) return;
const result = await webContainer.run(code);
setOutput(result);
};
if (isLoading) return <div>Loading Node.js environment...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={() => runCode('console.log("Hello!")')}>
Run Code
</button>
<pre>{output}</pre>
</div>
);
}
Provides Node.js container context to child components. Must wrap any components using useNodeContainer
.
Props:
children: ReactNode
- Child components
React hook to access the Node.js container.
Returns:
{
webContainer: NodeContainer | null; // Container instance
isLoading: boolean; // Loading state
error: Error | null; // Error state
}
NodeContainer.boot(): Promise<NodeContainer>
- Initialize the Node.js container and return a singleton instanceNodeContainer.teardown(): void
- Reset the singleton instance for complete reinitializationrun(code: string, options?: RunOptions): Promise<string>
- Execute Node.js code and return the captured outputinstallPackage(packageName: string): Promise<void>
- Install an npm package in the containerreadFile(path: string): Promise<string>
- Read a file from the virtual file systemwriteFile(path: string, content: string): Promise<void>
- Write a file to the virtual file systemreaddir(path: string): Promise<string[]>
- List the contents of a directorymkdir(path: string, options?: { recursive?: boolean }): Promise<void>
- Create a directory in the virtual file systemrm(path: string, options?: { recursive?: boolean, force?: boolean }): Promise<void>
- Remove a file or directory from the virtual file system
interface RunOptions {
filename?: string; // Filename for the code (determines TypeScript compilation)
packageJson?: object; // Custom package.json configuration
files?: Record<string, string>; // Additional files to mount
}
const container = await NodeContainer.boot();
// Create directories
await container.mkdir('/data');
await container.mkdir('/data/nested/path', { recursive: true });
// Write files
await container.writeFile('/data/config.json', '{"env":"production"}');
// List files
const files = await container.readdir('/data');
console.log(files); // ['config.json', 'nested']
// Read files
const content = await container.readFile('/data/config.json');
console.log(content); // {"env":"production"}
// Use in Node.js code
await container.run(`
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('/data/config.json', 'utf8'));
console.log('Environment:', config.env);
`);
// Remove files
await container.rm('/data/config.json');
await container.rm('/data', { recursive: true });
const container = await NodeContainer.boot();
// Install packages
await container.installPackage('lodash');
// Use in code
await container.run(`
const _ = require('lodash');
const result = _.chunk(['a', 'b', 'c', 'd'], 2);
console.log(result); // [['a', 'b'], ['c', 'd']]
`);
const container = await NodeContainer.boot();
// Run TypeScript code
const result = await container.run(
`
interface User {
name: string;
age: number;
}
const user: User = { name: 'Alice', age: 30 };
console.log(\`\${user.name} is \${user.age} years old\`);
`,
{ filename: 'script.ts' }
);
try {
await container.run(`
throw new Error('Something went wrong');
`);
} catch (error) {
console.error('Node.js error:', error.message);
}
This repository includes complete working examples:
A minimal example using plain JavaScript with Vite - perfect for understanding the core API.
cd examples/vanillajs
pnpm install
pnpm dev
Features:
- Simple HTML + JavaScript setup
- Interactive code editor
- Real-time code execution
- Cross-origin isolation headers configured
A comprehensive React application demonstrating hooks and providers.
cd examples/react
pnpm install
pnpm dev
Features:
- React hooks integration
- Context provider pattern
- CodeMirror editor
- Console output display
- Modern browser with SharedArrayBuffer support
- HTTPS in production (or localhost for development)
- Cross-origin isolation enabled
MIT @ Jimmy Moon ragingwind@gmail.com