Skip to content

examples-ai/node-code-container

Repository files navigation

node-code-container

Browser-based code execution environment for Node.js with TypeScript support and React bindings.

Features

  • 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

Installation

npm install @examples-ai/code-container
# or
yarn add @examples-ai/code-container
# or
pnpm add @examples-ai/code-container

Quick Start

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

Using with React

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>
  );
}

React API

NodeContainerProvider

Provides Node.js container context to child components. Must wrap any components using useNodeContainer.

Props:

  • children: ReactNode - Child components

useNodeContainer()

React hook to access the Node.js container.

Returns:

{
  webContainer: NodeContainer | null; // Container instance
  isLoading: boolean; // Loading state
  error: Error | null; // Error state
}

API Reference

  • NodeContainer.boot(): Promise<NodeContainer> - Initialize the Node.js container and return a singleton instance
  • NodeContainer.teardown(): void - Reset the singleton instance for complete reinitialization
  • run(code: string, options?: RunOptions): Promise<string> - Execute Node.js code and return the captured output
  • installPackage(packageName: string): Promise<void> - Install an npm package in the container
  • readFile(path: string): Promise<string> - Read a file from the virtual file system
  • writeFile(path: string, content: string): Promise<void> - Write a file to the virtual file system
  • readdir(path: string): Promise<string[]> - List the contents of a directory
  • mkdir(path: string, options?: { recursive?: boolean }): Promise<void> - Create a directory in the virtual file system
  • rm(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
}

Examples

File Operations

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 });

Package Installation

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']]
`);

TypeScript Support

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' }
);

Error Handling

try {
  await container.run(`
throw new Error('Something went wrong');
  `);
} catch (error) {
  console.error('Node.js error:', error.message);
}

Working Examples

This repository includes complete working examples:

Vanilla JavaScript Example

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

React Example

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

Browser Requirements

  • Modern browser with SharedArrayBuffer support
  • HTTPS in production (or localhost for development)
  • Cross-origin isolation enabled

License

MIT @ Jimmy Moon ragingwind@gmail.com

About

Node/TS Code Container, wrapping of web-container but very simple to use

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published