# @ehmpathy/as-command 中文文档

规范地址：https://npmcn.com/package/%40ehmpathy/as-command/

版本：1\.0\.5
npm 元数据更新时间：2025-11-02T22:15:04.005Z
中文译文更新时间：2026-11-14T00:10:34.821Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：49.7 kB，12 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=8\.0\.0
- 运行依赖：2 个
- 首次发布：2024-05-26T19:59:48.069Z
- 最新版本发布：2025-11-02T22:15:03.713Z
- 近 30 天下载量：2761（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：5（近 12 个月 0 个）

## 中文简介

很容易在成功坑内创建命令

## 安装

```sh
npm install @ehmpathy/as-command
```

也可以使用：`pnpm add @ehmpathy/as-command`、`yarn add @ehmpathy/as-command`、`bun add @ehmpathy/as-command`

## README

# 作为命令

![test](https://github.com/ehmpathy/as-command/workflows/test/badge.svg) ![publish](https://github.com/ehmpathy/as-command/workflows/publish/badge.svg)

很容易在成功坑内创建命令

## 安装

```sh
npm install @ehmpathy/as-command
```

## 使用量

### 默认输出

创建一个简单的命令,用自动记录和输出持续处理数据:

```ts
import { asCommand } from '@ehmpathy/as-command';
import { COMMANDS_OUTPUT_DIRECTORY } from './constants';

const command = asCommand(
  {
    name: 'processData',
    stage: process.env.STAGE || 'dev',
    dir: COMMANDS_OUTPUT_DIRECTORY,
    log,
  },
  async (input: { userId: string; date: string }, context) => {
    context.log.info('starting data processing', { userId: input.userId });

    // your business logic here
    const result = {
      processed: true,
      recordCount: 42,
      timestamp: new Date().toISOString(),
    };

    context.log.info('processing complete', { result });

    return result;
  },
);

// run directly
if (require.main === module) {
  void command({
    userId: 'user-123',
    date: '2024-01-15',
  });
}
```

**输出结构 :**

```
__tmp__/dev/processData/
└── 20240115.143022.a1b2c3d4.../
    ├── log.json      # all logs from the run
    └── out.json      # command output
```

### 定制产出

创建组织输出的复杂目录结构 :

```ts
const command = asCommand(
  {
    name: 'analyzeData',
    stage: 'prod',
    dir: COMMANDS_OUTPUT_DIRECTORY,
    log,
  },
  async (input: { datasetId: string }, context) => {
    // write to nested directories - they're created automatically
    await context.out.write({
      name: 'reports/analytics/user-metrics.json',
      data: JSON.stringify({ activeUsers: 1500 }),
    });

    await context.out.write({
      name: 'reports/analytics/revenue-breakdown.csv',
      data: 'Category,Amount\nSubscriptions,50000\nAds,25000',
    });

    await context.out.write({
      name: 'exports/raw-data.json',
      data: JSON.stringify({ records: [] }),
    });

    return { analyzed: true };
  },
);
```

**输出结构 :**

```
__tmp__/prod/analyzeData/
└── 20240115.143022.i9j0k1l2.../
    ├── log.json
    ├── out.json
    ├── reports/
    │   └── analytics/
    │       ├── user-metrics.json
    │       └── revenue-breakdown.csv
    └── exports/
        └── raw-data.json
```

## 概念

### 命令上下文

每个命令都收到一个 `context` 对象,使用下列方法:

#### `context.log`

记录不同级别的信息。 所有日志都写入控制台和 `log.json`数字 :

```ts
context.log.debug('debug message', { data: 'debug info' });
context.log.info('info message', { userId: 123 });
context.log.warn('warning message', { issue: 'potential problem' });
context.log.error('error message', { error: errorObject });
```

#### `context.out.write()`

将自定义文件写入命令的输出目录 :

```ts
const result = await context.out.write({
  name: 'report.csv', // supports nested paths: 'reports/analytics/data.csv'
  data: csvString, // string or Buffer
});

// result.path contains the full path to the written file
console.log(result.path);
```

### 输出目录结构

每个命令运行根据时间戳和输入散列创建一个独特的目录:

```
{dir}/__tmp__/{stage}/{command-name}/
└── {timestamp}.{input-hash}/
    ├── log.json    # all logs from the run
    ├── out.json    # command return value
    └── ...         # any files created with context.out.write()
```

**示例:**

```
/var/app/__tmp__/prod/process-orders/
├── 20240115.091530.a1b2c3d4e5f6.../
│   ├── log.json
│   ├── out.json
│   └── orders-summary.csv
└── 20240115.102045.a1b2c3d4e5f6.../  # same input, different time
    ├── log.json
    ├── out.json
    └── orders-summary.csv
```

### 输入散列

命令使用 SHA-256 自动散列输入。这可以:

-   **分解检测**: 相同的输入产生相同的散列
-   **审计线索**: 当同一操作多次运行时跟踪
-   **调试**: 快速找到前一个输入相同的运行

```ts
// these two runs will have the same hash in their directory names:
await command({ userId: '123', action: 'process' });
await command({ userId: '123', action: 'process' });

// this run will have a different hash:
await command({ userId: '456', action: 'process' });
```

## 常见问题

### @ehmpathy/as-command 是什么？

很容易在成功坑内创建命令

### 如何安装 @ehmpathy/as-command？

在项目目录运行 npm install @ehmpathy/as-command，或使用 pnpm add / yarn add / bun add。

### @ehmpathy/as-command 支持 TypeScript 吗？

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

### @ehmpathy/as-command 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @ehmpathy/as-command 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=8\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @ehmpathy/as-command 可以商用吗？

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

### @ehmpathy/as-command 的下载量有多少？

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

### @ehmpathy/as-command 还在维护吗？

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

