# @dhis2/cli-helpers-engine 中文文档

规范地址：https://npmcn.com/package/%40dhis2/cli-helpers-engine/

版本：3\.2\.2
npm 元数据更新时间：2024-05-07T15:56:01.391Z
中文译文更新时间：2026-11-12T06:12:35.479Z
软件包许可：BSD-3-Clause

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

原始 npm 页面：https://www.npmjs.com/package/%40dhis2/cli-helpers-engine
原文对照：https://npmcn.com/package/%40dhis2/cli-helpers-engine/?lang=original
项目主页：https://github.com/dhis2/cli-helpers-engine#readme
源码仓库：https://github.com/dhis2/cli-helpers-engine

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

- 包体积（解压后）：47.1 kB，32 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：\>=12
- 运行依赖：9 个
- 首次发布：2019-01-28T17:52:15.567Z
- 最新版本发布：2024-05-07T15:56:01.174Z
- 近 30 天下载量：15778（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：30（近 12 个月 0 个）

## 中文简介

用于创建D2 CLI模块的公用事业

## 安装

```sh
npm install @dhis2/cli-helpers-engine
```

也可以使用：`pnpm add @dhis2/cli-helpers-engine`、`yarn add @dhis2/cli-helpers-engine`、`bun add @dhis2/cli-helpers-engine`

## README

# cli- 帮助- 引擎

[![@dhis2/cli-style on npm](https://img.shields.io/npm/v/@dhis2/cli-helpers-engine.svg)](https://www.npmjs.com/package/@dhis2/cli-helpers-engine) [![travis.com build](https://img.shields.io/travis/com/dhis2/cli-helpers-engine.svg)](https://travis-ci.com/dhis2/cli-helpers-engine) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org/) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![Greenkeeper badge](https://badges.greenkeeper.io/dhis2/cli-helpers-engine.svg)](https://greenkeeper.io/)

> 这是插件模块在 [@dhis2/cli (英语)](https://github.com/dhis2/cli) 命令线界面生态系统.

## 几个公共公用事业:

这些帮助者假设一个节点.js CLI上下文. 还有其他帮手,但他们目前没有证件.

```js
const { reporter, chalk, prompt, exec } = require('@dhis2/cli-helpers-engine')

// These are wrappers around stdout and stderr which respect the --verbose and --quiet flags.  Some reporting options also prefix the line with a tag - see lib/reporter.js for all the options
reporter.print('This is a test') // Only printed if --quiet is not passed
reporter.print(chalk.dim('This is a less important test'))
reporter.print(
    chalk.green(
        `Chalk can be used to ${chalk.bold(
            'style text'
        )} which will be printed to the console.`
    )
)
reporter.info('This is something important') // prints to stdout in cyan: This is something important
reporter.error('An error occurred') // prints to stderr in red: [ERROR] An error occured
reporter.warn('Something non-critical went wrong') // prints to stderr in yellow: [WARNING] Something non-critical went wrong
reporter.debug('This will only be printed when --verbose is passed') // prints to stdout if --verbose in dim gray: [DEBUG] This will only be printed when --verbose is passed

// Use prompt to ask the user for input - it is a thin wrapper around `inquirer.prompt`, see https://github.com/SBoudrias/Inquirer.js
const answers = await prompt([
    {
        type: 'list',
        name: 'theme',
        message: 'What do you want to do?',
        choices: [
            'Order a pizza',
            'Make a reservation',
            new inquirer.Separator(),
            'Ask for opening hours',
            {
                name: 'Contact support',
                disabled: 'Unavailable at this time',
            },
            'Talk to the receptionist',
        ],
    },
    {
        type: 'list',
        name: 'size',
        message: 'What size do you need?',
        choices: ['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
        filter: function (val) {
            return val.toLowerCase()
        },
        when: function (answers) {
            return answers.theme === 'Order a pizza'
        },
    },
])
if (answers.theme === 'Order a pizza') {
    reporter.info(`Ordering a ${answers.size} pizza`)
} else {
    reporter.info(`Ok, let's ${answers.theme}`)
}

// Exec a function in the local shell environment, pass some arguments, set the current working directory, and capture the output as a string

const textContents = await exec({
    cmd: 'cat',
    args: ['./test.txt'],
    cwd: './myDirectory',
    captureOut: true,
})
```

你可以做更多的 与这些公用事业 -检查源代码 `./libs` 文件夹或许多 CLI 模块示例 [日记2/cli](https://github.com/dhis2/cli) 给灵感.

## 如何使用 d2 缓存

任意 CLI 命令即时 `@dhis2/cli-helpers-engine` 将会注入 `getCache` 参数。 这是一个强大的简单的缓存引擎,用于下载、缓存和访问全球文件 `d2` 缓存.

最实用的方法 `d2` 缓存是 `get`,它允许开发者获取远程URL,如果下载是zip文件,可选择将其取出,并存储在缓存中. 如果缓存中已经存在副本,则下载被跳过(除非 `force: true` 已指定:

```js
const { makeEntryPoint } = require('@dhis2/cli-helpers-engine')

const handler = async ({ force, getCache }) => {
    const cache = getCache()

    const url =
        'https://spreadsheets.google.com/feeds/list/1Fd-vBoJPjp5wdCyJc7d_LOJPOg5uqdzVa3Eq5-VFR-g/2/public/values?alt=json'

    // This will download a json file listing all countries which implement DHIS2 and store it in the cache.
    // It will *always* be re-downloaded, but if the download fails and a previous cache exists life goes on.
    const dataCachePath = 'dhis2-in-action-countries.json'
    try {
        await cache.get(url, dataCachePath, { force: true })
    } catch (e) {
        const exists = await cache.exists(dataCachePath)
        if (!exists) {
            reporter.error('Failed to download new in-action data, and no cached data exists')
            process.exit(1)
        }
        const modifiedTime = (await cache.stat(dataCachePath)).mtime.toISOString()
        reporter.debug(`Failed to update in-action data cache, using previously-cached data from ${modifiedTime}`)
    }

    // And now an example for a zip file
    const dbUrl =
        'https://databases.dhis2.org/sierra-leone/2.35.0/dhis2-db-sierra-leone.sql.gz'

    // This will download the demo database for 2.35.0 and store it in the cache.  The 'raw' option means the .gz file will NOT be unpacked, but rather stored directly on disk.  If a version of this file already exists in the cache, it will not be fetched again, unless the `force` option is passed to this command.
    await cache.get(dbUrl, 'databases/2.35.0.sql.gz', { raw: true, force: force })

    // List all currently-downloaded databases

    const dirStat = (await cache.exists('databases'))
        ? await cache.stat('databases')
        : null
    if (dirStat && dirStat.children) {
        Object.entries(dirStat.children)
            .forEach(([name, stat]) => {
                reporter.print(`${chalk.bold(name)} (${stat.size})`)
            })
    } else {
        reporter.print('No databases found')
    }
}

const command = {
    builder: yargs => {
        yargs.option('force', {
            alias: 'f',
            type: 'boolean',
            description: 'force re-download of all cached items',
            default: false
        }
    },
    handler
})
makeEntryPoint(command)
```

操作中的缓存示例,请检查它在 [d2 组](https://github.com/dhis2/cli/blob/master/packages/cluster/src/common.js#L11-L52) 财务报告和审定财务报表 [d2 调试缓存](https://github.com/dhis2/cli/blob/master/packages/main/src/commands/debug/cache.js)

## 报告问题

问题跟踪器可见于 [DHIS2 吉拉](https://jira.dhis2.org/) 下划线 [国 际](https://jira.dhis2.org/projects/CLI) 项目.

深链接 :

-   [错误](https://jira.dhis2.org/secure/CreateIssueDetails!init.jspa?pid=10703&issuetype=10006&components=11019)
-   [特性](https://jira.dhis2.org/secure/CreateIssueDetails!init.jspa?pid=10703&issuetype=10300&components=11019)
-   [任务](https://jira.dhis2.org/secure/CreateIssueDetails!init.jspa?pid=10703&issuetype=10003&components=11019)

## 常见问题

### @dhis2/cli-helpers-engine 是什么？

用于创建D2 CLI模块的公用事业

### 如何安装 @dhis2/cli-helpers-engine？

在项目目录运行 npm install @dhis2/cli-helpers-engine，或使用 pnpm add / yarn add / bun add。

### @dhis2/cli-helpers-engine 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/dhis2\_\_cli-helpers-engine 是否存在。

### @dhis2/cli-helpers-engine 支持 ESM 还是 CommonJS？

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

### @dhis2/cli-helpers-engine 需要什么版本的 Node\.js？

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

### @dhis2/cli-helpers-engine 可以商用吗？

@dhis2/cli-helpers-engine 使用 BSD-3-Clause 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。另外不得用原作者名义为衍生产品背书。以上为概括，不构成法律意见，请以许可原文为准。

### @dhis2/cli-helpers-engine 的下载量有多少？

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

### @dhis2/cli-helpers-engine 还在维护吗？

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

