Node.js Preset โ
Convenience helpers for running JavaScript/Node.js code in machinees.
TypeScript: NodeMachine Class โ
The NodeMachine class provides Node.js-specific methods.
typescript
import { NodeMachine } from 'smolvm';
const machine = await NodeMachine.create({ name: 'node-env' });
try {
// Run JavaScript code
const result = await machine.runCode(`
console.log("Node.js version:", process.version);
console.log("Platform:", process.platform);
console.log("Architecture:", process.arch);
`);
console.log(result.stdout);
// Run ES modules
const esmResult = await machine.runESM(`
const add = (a, b) => a + b;
console.log("2 + 3 =", add(2, 3));
`);
console.log(esmResult.stdout);
// Check Node.js version
const version = await machine.version();
console.log(version); // "22.x.x"
// Install packages
await machine.npm(['lodash', 'axios']);
// Run with installed packages
const withPackages = await machine.runCode(`
const _ = require('lodash');
console.log(_.chunk([1, 2, 3, 4, 5], 2));
`);
} finally {
await machine.stop();
await machine.delete();
}Methods โ
| Method | Description |
|---|---|
runCode(code) | Execute CommonJS code |
runESM(code) | Execute ES module code |
runFile(path) | Execute a JavaScript file |
npm(packages) | Install packages with npm |
version() | Get Node.js version |
Python: Preset Function โ
python
from smolvm.presets import node_machine
# Execute JavaScript code
result = await node_machine("""
console.log("Node.js version:", process.version);
const data = { message: "Hello from Node.js!" };
console.log(JSON.stringify(data, null, 2));
""")
print(result.stdout)CommonJS vs ES Modules โ
CommonJS (Default) โ
typescript
const result = await machine.runCode(`
const fs = require('fs');
const path = require('path');
console.log(path.join('/tmp', 'test.txt'));
`);ES Modules โ
typescript
const result = await machine.runESM(`
import { readFileSync } from 'fs';
import { join } from 'path';
console.log(join('/tmp', 'test.txt'));
`);Installing Packages โ
typescript
const machine = await NodeMachine.create({ name: 'with-packages' });
// Install packages
await machine.npm(['express', 'cors', 'helmet']);
// Use them
const result = await machine.runCode(`
const express = require('express');
const cors = require('cors');
// Just verify imports work
console.log('Express version:', require('express/package.json').version);
console.log('Packages loaded successfully!');
`);TypeScript Execution โ
For TypeScript, use ts-node or compile first:
typescript
const machine = await NodeMachine.create({ name: 'typescript' });
// Install TypeScript tools
await machine.npm(['typescript', 'ts-node', '@types/node']);
// Run TypeScript with ts-node
const result = await machine.runCode(`
const { execSync } = require('child_process');
const code = \`
interface User {
name: string;
age: number;
}
const user: User = { name: "Alice", age: 30 };
console.log(user);
\`;
require('fs').writeFileSync('/tmp/test.ts', code);
console.log(execSync('npx ts-node /tmp/test.ts').toString());
`);HTTP Server Example โ
typescript
const machine = await NodeMachine.create({
name: 'http-server',
ports: [{ host: 3000, guest: 3000 }]
});
await machine.npm(['express']);
// Start server in background
machine.exec(['node', '-e', `
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ message: 'Hello from machine!' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
`]);
// Server is now accessible at localhost:3000Working with Files โ
typescript
const machine = await NodeMachine.create({
name: 'file-processor',
mounts: [
{ source: '/data/input', target: '/input', readonly: true },
{ source: '/data/output', target: '/output' }
]
});
const result = await machine.runCode(`
const fs = require('fs');
const path = require('path');
// Read input files
const files = fs.readdirSync('/input');
console.log('Input files:', files);
// Process each file
for (const file of files) {
const content = fs.readFileSync(path.join('/input', file), 'utf8');
const processed = content.toUpperCase();
fs.writeFileSync(path.join('/output', file), processed);
}
console.log('Processing complete!');
`);JSON Processing โ
typescript
const machine = await NodeMachine.create({ name: 'json-processor' });
const result = await machine.runCode(`
const data = {
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
};
// Transform data
const transformed = data.users.map(u => ({
...u,
email: \`\${u.name.toLowerCase()}@example.com\`
}));
console.log(JSON.stringify(transformed, null, 2));
`);
const output = JSON.parse(result.stdout);
console.log(output);