SuperAPI AI 工具集

node-cli

编程与开发

查看项目

更新于 10-16 22:15

技能介绍

用途

node-cli 提供构建 Node.js 命令行工具(CLI)的模式与约定,用于在创建或修改 Node.js CLI、添加 Commander 命令、接入 update-notifier,或需要了解如何组织 CLI 入口点与 src 目录时参考。

主要能力

src 目录结构

技能给出了一套推荐的目录布局:

src/
├── index.ts              # Entry point — wires Commander, calls updateNotifier
├── update-notifier.d.ts  # Type shim for update-notifier package
├── commands/             # One file per CLI command
│   ├── add.ts
│   └── remove.ts
├── lib/                  # Pure domain logic, no Commander concerns
│   ├── github.ts         # single-file feature → stays flat
│   ├── linker.ts
│   └── push/             # 2+ files → grouped into a feature folder, prefix dropped
│       ├── index.ts      # barrel: re-exports the feature's public surface
│       ├── workflow.ts
│       └── validation.ts
└── utils/                # Generic helpers — mix flat files and nested groups freely
    ├── format.ts         # flat single-purpose helper
    └── fs/               # related helpers grouped under one folder
        ├── read.ts
        └── write.ts
tests/                    # Mirrors src/ structure, one test file per module
├── add.test.ts
└── linker.test.ts

相关约定包括:

  • commands/:每个文件导出一个 Command 实例;所有 CLI 相关关注点(提示、标志、输出)都放在这里。
  • lib/:与框架无关的辅助函数,由命令导入;保持可独立测试。
  • 目录不必保持扁平。默认让一个功能保持扁平,只有当它拥有 2 个以上文件时才将其归入文件夹——只放一个文件的文件夹只是噪音。分组时,文件夹已经命名了该功能,因此从文件名中去掉冗余前缀(lib/push/workflow.ts,而不是 lib/push/push-workflow.ts),并使用 dir/index.ts 作为功能的公共接口(一个 barrel,重新导出命令所导入的内容;或者对于 provider 风格的接缝,就是接口/契约本身)。命令导入文件夹,而不是其内部文件:import { planPush } from '../lib/push/index.js',这样每个功能的内部文件拆分可以变化而不影响调用点。

入口点结构

#!/usr/bin/env node
import { Command } from 'commander'
import updateNotifier from 'update-notifier'
import packageJson from '../package.json' with { type: 'json' }

// Call before parseAsync — notify() defers display to process exit so it
// never interleaves with command output.
updateNotifier({ pkg: packageJson }).notify()

const program = new Command('your-cli')
  .description('...')
  .version(packageJson.version)

program.addCommand(fooCommand)

await program.parseAsync()

测试 CLI 接线

保持可执行入口点与测试接缝相互独立。如果 src/index.ts 在顶层调用 parseAsync(),则将其视为仅可执行:测试应从 src/commands/* 导入命令工厂,组装一个本地 Command,并传入受控的 argv。不要在测试中导入顶层可执行入口点,因为它会解析测试运行器的 process.argv。

// src/commands/run.ts
import { Command } from 'commander'

export interface RunDispatch {
  runBatch(): Promise<void> | void
}

export function createRunCommand(dispatch: RunDispatch): Command {
  return new Command('run').action(async () => {
    await dispatch.runBatch()
  })
}
// tests/cli.test.ts
import { Command } from 'commander'
import { describe, expect, test, vi } from 'vitest'
import { createRunCommand } from '../src/commands/run'

test('dispatches run', async () => {
  const dispatch = { runBatch: vi.fn() }
  const program = new Command('your-cli')
  program.addCommand(createRunCommand(dispatch))

  await program.parseAsync(['node', 'your-cli', 'run'])

  expect(dispatch.runBatch).toHaveBeenCalledOnce()
})

对于较大的 CLI,第二种常见模式是一个轻量的 bin 文件,导入可测试的 run(argv) 或 execute(argv) 模块。当 CLI 有大量启动行为、需要围绕退出码进行集成式测试,或者还暴露公共库 API 时,使用这种方式。

更新通知

使用 update-notifier 包。它会自动处理后台检查(24 小时间隔)、状态持久化、CI/TTY/NO_UPDATE_NOTIFIER 退出选项。

pnpm add update-notifier

在哪里调用: index.ts 顶部,在 program.parseAsync() 之前——而不是在 postAction 钩子中。

为什么在 parse 之前: notify() 默认 defer: true,会注册一个 process.on('exit') 监听器。将其放在 parseAsync() 之前可确保无论运行哪个命令,监听器始终被注册。

类型 shim(该包不附带 .d.ts):

// src/update-notifier.d.ts
declare module 'update-notifier' {
  interface Package { name: string; version: string }
  interface Options { pkg: Package; updateCheckInterval?: number; distTag?: string }
  interface NotifyOptions { defer?: boolean; message?: string; isGlobal?: boolean }
  interface Notifier { notify(options?: NotifyOptions): void }
  export default function updateNotifier(options: Options): Notifier
}

推荐技术栈

关注点 包
CLI 框架 commander
交互式提示 @inquirer/prompts
更新通知 update-notifier
语言 TypeScript
测试运行器 vitest
版本号提升 bumpp — 一步完成提升 package.json、提交、打标签和推送
打包器 tsdown
诊断(结构化错误/警告) nostics — 定义一组诊断代码目录,包含稳定名称、消息、修复方案和文档 URL

package.json 要点

{
  "type": "module",
  "bin": { "your-cli": "./dist/index.js" },
  "engines": { "node": "^24.0.0" }
}

GitHub 工作流

如需结合 npm 发布与变更日志生成的完整端到端工作流,如果本地已安装该技能,请参阅 automate-npm-release/EXAMPLE_WORKFLOW.yml。

使用方式

该技能以模式与约定文档的形式提供,供在创建或修改 Node.js CLI 时参考。具体安装或调用方式暂未提供。

适用场景

  • 创建或修改 Node.js CLI 工具
  • 添加 Commander 命令
  • 接入 update-notifier 更新通知
  • 需要了解如何组织 CLI 入口点或 src 目录结构

限制

资料未提供该技能的具体安装方式、运行命令、收费或价格信息,也未说明其平台支持范围。