@ computesdk/ just- bash (帮助)
刚刚巴什 计算 SDK 的提供者 - 本地沙盒被用虚拟文件系统执行 。 不需要外部服务、集装箱或认证.
安装
npm install @computesdk/just-bash
快速启动
import { justBash } from '@computesdk/just-bash';
const compute = justBash({});
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('echo "Hello" | tr a-z A-Z');
console.log(result.stdout); // "HELLO"
await sandbox.destroy();
配置
环境变量
不需要环境变量。 只是巴什完全在当地运行.
配置选项
interface JustBashConfig {
/** Enable Python support via pyodide (disabled by default) */
python?: boolean;
/** Initial files to populate in the virtual filesystem */
files?: Record<string, string>;
/** Initial environment variables */
env?: Record<string, string>;
/** Working directory (defaults to /home/user) */
cwd?: string;
/** Custom filesystem implementation (see Filesystem Backends below) */
fs?: IFileSystem;
/** Custom commands created with defineCommand() (see Custom Commands below) */
customCommands?: CustomCommand[];
/** Network configuration for curl (disabled by default) */
network?: NetworkConfig;
}
文件系统后端
默认情况下, Just-bash 使用 记忆Fs ——纯粹的内存文件系统. 您可以根据您的使用大小写在替代后端中互换 :
内存( 默认)
所有文件都生活在记忆中. 快速,决定性,完全隔离.
const compute = justBash({}); // InMemoryFs is the default
重叠Fs( 复制到写上)
从磁盘上的真实目录读取; 写入内存 。 基础目录从未被修改 .
import { OverlayFs } from 'just-bash';
const compute = justBash({
fs: new OverlayFs({ root: '/path/to/project' }),
cwd: '/path/to/project',
});
ReadWriteFs (直接磁盘访问)
读取和写作直接到一个真实的目录. 谨慎使用——变化是真实的.
import { ReadWriteFs } from 'just-bash';
const compute = justBash({
fs: new ReadWriteFs({ root: '/tmp/sandbox' }),
});
可挂载Fs( 组成多文件系统)
在不同路径上挂起不同的文件系统后端 .
import { MountableFs, InMemoryFs } from 'just-bash';
import { OverlayFs } from 'just-bash';
const compute = justBash({
fs: new MountableFs({
base: new InMemoryFs(),
mounts: [
{ mountPoint: '/project', filesystem: new OverlayFs({ root: '/real/project' }) },
],
}),
cwd: '/project',
});
自定义命令
您可以使用自定义命令来扩展 Just- bash defineCommand()数字 :
import { justBash } from '@computesdk/just-bash';
import { defineCommand } from 'just-bash';
const hello = defineCommand('hello', async (args, ctx) => {
const name = args[0] || 'world';
return {
stdout: `Hello, ${name}!\n`,
stderr: '',
exitCode: 0,
};
});
const compute = justBash({ customCommands: [hello] });
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('hello Alice');
console.log(result.stdout); // "Hello, Alice!\n"
自定义命令接收上下文对象( E)ctx(a) 获取:
ctx.fs——虚拟文件系统ctx.cwd——当前工作目录ctx.env——环境变量ctx.stdin——标准输入ctx.exec(command)——运行子命令
API 参考
代码执行
// Execute bash scripts
const result = await sandbox.runCommand(`
for i in 1 2 3; do
echo "Number: $i"
done
`);
console.log(result.stdout);
// Number: 1
// Number: 2
// Number: 3
// Execute Python code (requires python: true in config)
const compute = justBash({ python: true });
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand(`python - <<'PY'
import json
data = {"message": "Hello from Python"}
print(json.dumps(data))
PY`);
命令执行
// Pipes and text processing
const result = await sandbox.runCommand('echo -e "banana\\napple\\ncherry" | sort');
console.log(result.stdout); // "apple\nbanana\ncherry\n"
// JSON processing with jq
await sandbox.filesystem.writeFile('/data.json', '[{"name":"Alice"},{"name":"Bob"}]');
const result = await sandbox.runCommand('cat /data.json | jq ".[].name"');
// Environment variables per command
const result = await sandbox.runCommand('echo $MY_VAR', { env: { MY_VAR: 'hello' } });
// Working directory per command
const result = await sandbox.runCommand('cat config.json', { cwd: '/app' });
文件系统操作
// Write file
await sandbox.filesystem.writeFile('/tmp/hello.txt', 'Hello World');
// Read file
const content = await sandbox.filesystem.readFile('/tmp/hello.txt');
// Create directory
await sandbox.filesystem.mkdir('/tmp/data');
// List directory contents
const files = await sandbox.filesystem.readdir('/tmp');
// Check if file exists
const exists = await sandbox.filesystem.exists('/tmp/hello.txt');
// Remove file or directory
await sandbox.filesystem.remove('/tmp/hello.txt');
沙盒管理
// Get sandbox info
const info = await sandbox.getInfo();
console.log(info.id, info.provider, info.status);
// List all active sandboxes
const sandboxes = await compute.instances.list();
// Get sandbox by ID
const existing = await compute.instances.getById('sandbox-id');
// Destroy sandbox
await sandbox.destroy();
人口稠密前的文件
const compute = justBash({
files: {
'/app/config.json': '{"port": 3000}',
'/app/data.csv': 'name,age\nAlice,25\nBob,30',
},
env: {
APP_ENV: 'production',
},
cwd: '/app',
});
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('cat config.json');
console.log(result.stdout); // {"port": 3000}
内建命令
just-bash包括60+内置命令:
| 类别 | 图标 |
|---|---|
| 文件操作 | cat, (中文(简体) ), cp, (中文(简体) ), ls, (中文(简体) ), mkdir, (中文(简体) ), mv, (中文(简体) ), rm, (中文(简体) ), touch, (中文(简体) ), tree, (中文(简体) ), ln, (中文(简体) ), find |
| 文本处理 | awk, (中文(简体) ), grep, (中文(简体) ), sed, (中文(简体) ), cut, (中文(简体) ), sort, (中文(简体) ), uniq, (中文(简体) ), wc, (中文(简体) ), head, (中文(简体) ), tail, (中文(简体) ), tr |
| 数据处理 | jq (杰森语), yq (YAML/XML), (中文(简体) ), sqlite3 (SQLite), CSV 工具 |
| 压缩 | gzip, (中文(简体) ), tar |
| 公用事业 | echo, (中文(简体) ), printf, (中文(简体) ), date, (中文(简体) ), seq, (中文(简体) ), timeout, (中文(简体) ), basename, (中文(简体) ), dirname |
| 贝壳 | export, (中文(简体) ), source, (中文(简体) ), alias, (中文(简体) ), test, (中文(简体) ), read, (中文(简体) ), set, (中文(简体) ), unset |
处理错误
import { justBash } from '@computesdk/just-bash';
const compute = justBash({});
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('cat /nonexistent');
if (result.exitCode !== 0) {
console.error('Command failed:', result.stderr);
}
// getUrl throws since just-bash has no network
try {
await sandbox.getUrl({ port: 3000 });
} catch (error) {
console.error(error.message); // "just-bash is a local sandbox without network capabilities..."
}
实例
数据管道
import { justBash } from '@computesdk/just-bash';
const compute = justBash({});
const sandbox = await compute.instances.create();
// Create CSV data
await sandbox.filesystem.writeFile('/data/sales.csv',
'product,quantity,price\nWidget,100,9.99\nGadget,50,24.99\nDoohickey,200,4.99'
);
// Process with awk
const result = await sandbox.runCommand(
'cat /data/sales.csv | tail -n +2 | awk -F, \'{ total += $2 * $3 } END { printf "Total revenue: $%.2f\\n", total }\''
);
console.log(result.stdout); // Total revenue: $3247.50
await sandbox.destroy();
JSON 处理
import { justBash } from '@computesdk/just-bash';
const compute = justBash({
files: {
'/data/users.json': JSON.stringify([
{ name: 'Alice', age: 30, role: 'admin' },
{ name: 'Bob', age: 25, role: 'user' },
{ name: 'Charlie', age: 35, role: 'admin' },
]),
},
});
const sandbox = await compute.instances.create();
// Filter admins and extract names
const result = await sandbox.runCommand(
'cat /data/users.json | jq \'[.[] | select(.role == "admin") | .name]\''
);
console.log(result.stdout); // ["Alice", "Charlie"]
await sandbox.destroy();
脚本执行
import { justBash } from '@computesdk/just-bash';
const compute = justBash({});
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand(`
#!/bin/bash
count=0
for f in /proc/self/status /etc/hostname; do
if test -f "$f"; then
count=$((count + 1))
fi
done
echo "Found $count system files"
`);
console.log(result.stdout);
await sandbox.destroy();
限制
- 无网络访问 - 说吧
getUrl()不支持;curl需要明确network配置 - 无真实进程 - 命令在TypeScript中解释,而不是作为真正的OS进程执行
- 无本地节点.js 运行时 - 使用 shell 命令; 此提供者为先击后击, 不运行一个真正的节点. js VM
- 默认记忆 - 文件不持久,除非你使用
OverlayFs, (中文(简体) ),ReadWriteFs,或MountableFs - 通过 Pyodide 活体 - 需要Python支持
python: true并使用 p(基于网络大会)
何时使用 Just- bash
- 测试和开发 - 促进发展的快速、无成本的沙盒和CI
- AI 代理工具 - 为AI代码生成安全执行
- 离线环境 - 不需要网络或API密钥
- 单位测试 - 确定性的、孤立的试验环境
许可证
麻省理工学院