Language Examples
Language Examples
Section titled “Language Examples”Complete, tested examples showing multi-file project deployment for each supported language. Each example includes the full project structure, deployment commands, and execution.
JavaScript (Node.js)
Section titled “JavaScript (Node.js)”Project Structure
Section titled “Project Structure”js-project/├── package.json├── index.js└── utils/ └── math.js{"name": "js-test","version": "1.0.0","dependencies": { "lodash": "^4.17.21"}}module.exports = {add: (a, b) => a + b,multiply: (a, b) => a * b,square: (x) => x * x};const _ = require('lodash');const math = require('./utils/math');
console.log('=== JS Multi-File Test ===');console.log('Math.add(2, 3):', math.add(2, 3));console.log('Math.square(4):', math.square(4));console.log('Lodash chunk:', JSON.stringify(_.chunk([1,2,3,4], 2)));console.log('✅ JS test passed!');Deployment
Section titled “Deployment”# 1. Create session with dependenciescurl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "node", "session_id": "js-project", "persistent": true, "setup": { "npm": ["lodash"] } }'
# 2. Wait for setup to complete (20-30 seconds)curl https://anewera.dev/api/sessions/js-project | jq '.setup_status'# Should return: "completed"
# 3. Upload files./era-upload.sh js-project ./js-project
# 4. Run the codecurl -X POST https://anewera.dev/api/sessions/js-project/run \ -H "Content-Type: application/json" \ -d '{"code": "require(\"./index.js\")"}'Expected Output:
=== JS Multi-File Test ===Math.add(2, 3): 5Math.square(4): 16Lodash chunk: [[1,2],[3,4]]✅ JS test passed!TypeScript
Section titled “TypeScript”Project Structure
Section titled “Project Structure”ts-project/├── package.json├── index.ts└── utils/ └── string.ts{"name": "ts-test","version": "1.0.0","dependencies": { "axios": "^1.6.0"}}export function capitalize(str: string): string {return str.charAt(0).toUpperCase() + str.slice(1);}
export function reverse(str: string): string {return str.split('').reverse().join('');}import { capitalize, reverse } from './utils/string';
console.log('=== TS Multi-File Test ===');console.log('Capitalize:', capitalize('hello'));console.log('Reverse:', reverse('world'));console.log('Type check works:', typeof capitalize === 'function');console.log('✅ TS test passed!');Deployment
Section titled “Deployment”# 1. Create session with dependenciescurl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "typescript", "session_id": "ts-project", "persistent": true, "setup": { "npm": ["axios"] } }'
# 2. Wait for setupcurl https://anewera.dev/api/sessions/ts-project | jq '.setup_status'
# 3. Upload files (Python script is faster for multiple files)python3 era_upload.py ts-project ./ts-project
# 4. Run the code (tsx is used automatically for .ts files)curl -X POST https://anewera.dev/api/sessions/ts-project/run \ -H "Content-Type: application/json" \ -d '{"code": "require(\"./index.ts\")"}'Expected Output:
=== TS Multi-File Test ===Capitalize: HelloReverse: dlrowType check works: true✅ TS test passed!Python
Section titled “Python”Project Structure
Section titled “Project Structure”py-project/├── requirements.txt├── main.py└── utils/ ├── __init__.py ├── math.py └── string.pyrequests>=2.31.0from .math import add, multiplyfrom .string import upper, lower
__all__ = ['add', 'multiply', 'upper', 'lower']def add(a, b): return a + b
def multiply(a, b): return a * bdef upper(s): return s.upper()
def lower(s): return s.lower()from utils import add, multiply, upper, lowerimport requests
print('=== Python Multi-File Test ===')print(f'Add(2, 3): {add(2, 3)}')print(f'Multiply(4, 5): {multiply(4, 5)}')print(f'Upper("hello"): {upper("hello")}')print(f'Requests available: {requests.__version__}')print('✅ Python test passed!')Deployment
Section titled “Deployment”# 1. Create session with requirements.txtREQUIREMENTS=$(cat requirements.txt)
curl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "python", "session_id": "py-project", "persistent": true, "setup": { "pip": { "requirements": "'"$REQUIREMENTS"'" } } }'
# 2. Wait for pip install to completecurl https://anewera.dev/api/sessions/py-project | jq '.setup_status'
# 3. Upload filespython3 era_upload.py py-project ./py-project
# 4. Run the main scriptcurl -X POST https://anewera.dev/api/sessions/py-project/run \ -H "Content-Type: application/json" \ -d '{"code": "exec(open(\"main.py\").read())"}'Expected Output:
=== Python Multi-File Test ===Add(2, 3): 5Multiply(4, 5): 20Upper("hello"): HELLORequests available: 2.31.0✅ Python test passed!Project Structure
Section titled “Project Structure”deno-project/├── main.ts└── utils/ └── helpers.tsexport function greet(name: string): string {return `Hello, ${name}!`;}
export function double(n: number): number {return n * 2;}import { greet, double } from './utils/helpers.ts';
console.log('=== Deno Multi-File Test ===');console.log('Greet:', greet('Deno'));console.log('Double 5:', double(5));console.log('Deno version:', Deno.version.deno);console.log('✅ Deno test passed!');Deployment
Section titled “Deployment”# 1. Create session (no dependencies needed)curl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "deno", "session_id": "deno-project", "persistent": true }'
# 2. Upload files./era-upload.sh deno-project ./deno-project
# 3. Run with Denocurl -X POST https://anewera.dev/api/sessions/deno-project/run \ -H "Content-Type: application/json" \ -d '{"code": "/usr/local/bin/deno run --allow-read main.ts"}'Expected Output:
=== Deno Multi-File Test ===Greet: Hello, Deno!Double 5: 10Deno version: 1.40.0✅ Deno test passed!Advanced Examples
Section titled “Advanced Examples”Express.js API
Section titled “Express.js API”Complete REST API with multiple routes:
{"name": "express-api","version": "1.0.0","dependencies": { "express": "^4.18.0", "body-parser": "^1.20.0", "cors": "^2.8.5"}}const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const usersRouter = require('./routes/users');const postsRouter = require('./routes/posts');
const app = express();const port = process.env.PORT || 3000;
app.use(cors());app.use(bodyParser.json());
app.get('/', (req, res) => {res.json({ message: 'ERA Express API', version: '1.0.0' });});
app.use('/api/users', usersRouter);app.use('/api/posts', postsRouter);
app.listen(port, () => {console.log(`Server running on port ${port}`);});const express = require('express');const router = express.Router();
// In-memory storeconst users = [{ id: 1, name: 'Alice', email: 'alice@example.com' },{ id: 2, name: 'Bob', email: 'bob@example.com' }];
router.get('/', (req, res) => {res.json(users);});
router.get('/:id', (req, res) => {const user = users.find(u => u.id === parseInt(req.params.id));if (!user) return res.status(404).json({ error: 'User not found' });res.json(user);});
router.post('/', (req, res) => {const newUser = { id: users.length + 1, name: req.body.name, email: req.body.email};users.push(newUser);res.status(201).json(newUser);});
module.exports = router;const express = require('express');const router = express.Router();
const posts = [{ id: 1, title: 'First Post', author: 'Alice' },{ id: 2, title: 'Second Post', author: 'Bob' }];
router.get('/', (req, res) => {res.json(posts);});
router.get('/:id', (req, res) => {const post = posts.find(p => p.id === parseInt(req.params.id));if (!post) return res.status(404).json({ error: 'Post not found' });res.json(post);});
module.exports = router;Deployment:
# Create with dependenciescurl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "node", "session_id": "express-api", "persistent": true, "allowPublicAccess": true, "setup": { "npm": ["express", "body-parser", "cors"] } }'
# Upload project./era-upload.sh express-api ./express-api
# Store server codecurl -X PUT https://anewera.dev/api/sessions/express-api/code \ -H "Content-Type: application/json" \ -d '{"code": "require(\"./server.js\")"}'
# Get public URLcurl https://anewera.dev/api/sessions/express-api/host?port=3000
# Access APIcurl https://anewera.dev/proxy/express-api/3000/api/usersPython Data Processing Pipeline
Section titled “Python Data Processing Pipeline”pandas>=2.0.0numpy>=1.24.0requests>=2.31.0import pandas as pdimport numpy as npfrom processors.cleaner import clean_datafrom processors.analyzer import analyze_datafrom utils.logger import log
def main(): log("Starting data pipeline...")
# Generate sample data data = pd.DataFrame({ 'id': range(1, 101), 'value': np.random.randint(1, 100, 100), 'category': np.random.choice(['A', 'B', 'C'], 100) })
log(f"Generated {len(data)} records")
# Clean data cleaned = clean_data(data) log(f"Cleaned: {len(cleaned)} records")
# Analyze results = analyze_data(cleaned) log(f"Analysis complete: {results}")
print("✅ Pipeline completed successfully!")
if __name__ == "__main__": main()import pandas as pd
def clean_data(df): """Remove duplicates and null values.""" return df.dropna().drop_duplicates()def analyze_data(df): """Compute basic statistics.""" return { 'count': len(df), 'mean_value': df['value'].mean(), 'categories': df['category'].value_counts().to_dict() }from datetime import datetime
def log(message): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"[{timestamp}] {message}")Deployment:
# Create with data science packagesREQUIREMENTS=$(cat requirements.txt)
curl -X POST https://anewera.dev/api/sessions \ -H "Content-Type: application/json" \ -d '{ "language": "python", "session_id": "data-pipeline", "persistent": true, "setup": { "pip": { "requirements": "'"$REQUIREMENTS"'" } } }'
# Upload projectpython3 era_upload.py data-pipeline ./data-pipeline
# Run pipelinecurl -X POST https://anewera.dev/api/sessions/data-pipeline/run \ -H "Content-Type: application/json" \ -d '{"code": "exec(open(\"pipeline.py\").read())"}'Testing Your Project
Section titled “Testing Your Project”Use these test scripts to validate your deployment:
Quick Test Script
Section titled “Quick Test Script”#!/bin/bash# test-project.shSESSION_ID="$1"ENTRY_POINT="$2"
echo "Testing session: $SESSION_ID"
# Check filesecho "Files uploaded:"curl -s "https://anewera.dev/api/sessions/$SESSION_ID/files" | jq '.files[].path'
# Run codeecho "Running code..."curl -s -X POST "https://anewera.dev/api/sessions/$SESSION_ID/run" \-H "Content-Type: application/json" \-d "{"code": "$ENTRY_POINT"}" | jq '.'Usage:
chmod +x test-project.sh./test-project.sh my-project "require('./index.js')"Common Patterns
Section titled “Common Patterns”Importing Local Modules
Section titled “Importing Local Modules”JavaScript/TypeScript:
// Relative imports work as expectedconst utils = require('./utils/helpers');import { func } from './lib/module';Python:
# Package imports work as expectedfrom utils import helperfrom .local_module import functionDeno:
// Must include .ts extensionimport { func } from './utils/helpers.ts';Working with Data Files
Section titled “Working with Data Files”// JavaScriptconst fs = require('fs');const data = JSON.parse(fs.readFileSync('./data/config.json', 'utf8'));# Pythonimport jsonwith open('data/config.json') as f: data = json.load(f)Environment Variables
Section titled “Environment Variables”// Access ERA environment variablesconst sessionId = process.env.ERA_SESSION_ID;const language = process.env.ERA_LANGUAGE;# Pythonimport ossession_id = os.getenv('ERA_SESSION_ID')language = os.getenv('ERA_LANGUAGE')Next Steps
Section titled “Next Steps”- See Multi-File Projects for complete deployment workflows
- Learn about Code Management for updating code
- Check Callbacks & Webhooks for making projects accessible via URLs