# @computesdk/just-bash 中文文档

规范地址：https://npmcn.com/package/%40computesdk/just-bash/

版本：0\.4\.33
npm 元数据更新时间：2026-11-06T13:39:36.800Z
中文译文更新时间：2026-11-10T15:03:09.164Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40computesdk/just-bash
原文对照：https://npmcn.com/package/%40computesdk/just-bash/?lang=original
项目主页：https://www.computesdk.com/
源码仓库：https://github.com/computesdk/computesdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：43.5 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- peer 依赖：just-bash \>=2\.0\.0
- 首次发布：2026-03-04T17:40:02.710Z
- 最新版本发布：2026-11-06T13:39:36.398Z
- 近 30 天下载量：3892（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：37（近 12 个月 37 个）

## 中文简介

just-bash 计算SDK 提供商 - 本地沙箱相撞执行虚拟文件系统

## 安装

```sh
npm install @computesdk/just-bash
```

也可以使用：`pnpm add @computesdk/just-bash`、`yarn add @computesdk/just-bash`、`bun add @computesdk/just-bash`

## README

# @ computesdk/ just- bash (帮助)

[刚刚巴什](https://justbash.dev/) 计算 SDK 的提供者 - 本地沙盒被用虚拟文件系统执行 。 不需要外部服务、集装箱或认证.

## 安装

```bash
npm install @computesdk/just-bash
```

## 快速启动

```typescript
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();
```

## 配置

### 环境变量

不需要环境变量。 只是巴什完全在当地运行.

### 配置选项

```typescript
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** ——纯粹的内存文件系统. 您可以根据您的使用大小写在替代后端中互换 :

### 内存( 默认)

所有文件都生活在记忆中. 快速,决定性,完全隔离.

```typescript
const compute = justBash({}); // InMemoryFs is the default
```

### 重叠Fs( 复制到写上)

从磁盘上的真实目录读取; 写入内存 。 基础目录从未被修改 .

```typescript
import { OverlayFs } from 'just-bash';

const compute = justBash({
  fs: new OverlayFs({ root: '/path/to/project' }),
  cwd: '/path/to/project',
});
```

### ReadWriteFs (直接磁盘访问)

读取和写作直接到一个真实的目录. 谨慎使用——变化是真实的.

```typescript
import { ReadWriteFs } from 'just-bash';

const compute = justBash({
  fs: new ReadWriteFs({ root: '/tmp/sandbox' }),
});
```

### 可挂载Fs( 组成多文件系统)

在不同路径上挂起不同的文件系统后端 .

```typescript
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()`数字 :

```typescript
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 参考

### 代码执行

```typescript
// 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`);
```

### 命令执行

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

### 文件系统操作

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

### 沙盒管理

```typescript
// 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();
```

### 人口稠密前的文件

```typescript
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` |

## 处理错误

```typescript
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..."
}
```

## 实例

### 数据管道

```typescript
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 处理

```typescript
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();
```

### 脚本执行

```typescript
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密钥
-   **单位测试** - 确定性的、孤立的试验环境

## 许可证

麻省理工学院

## 常见问题

### @computesdk/just-bash 是什么？

just-bash 计算SDK 提供商 - 本地沙箱相撞执行虚拟文件系统

### 如何安装 @computesdk/just-bash？

在项目目录运行 npm install @computesdk/just-bash，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：just-bash（\>=2\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @computesdk/just-bash 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @computesdk/just-bash 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @computesdk/just-bash 可以商用吗？

@computesdk/just-bash 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @computesdk/just-bash 的下载量有多少？

根据 npm 官方下载统计，@computesdk/just-bash 在 2026/10/11 – 2026/11/09 这 30 天内被下载 3,892 次，日均约 130 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @computesdk/just-bash 还在维护吗？

最新版本 0\.4\.33 发布于 2026/11/06（4 天前）；至今共发布 37 个版本，其中过去 12 个月发布了 37 个；首次发布于 2026/03/05。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

