@gustavnikolaj/async-main-wrap

中文文档
4.0.0发布于 2021/07/26ISCCommonJS零依赖近 30 天下载 5.2万

Simple CLI tool wrapper.

原始使用文档
文档目录6 节
  1. Pass in your output channels
  2. Use with arguments parser
  3. Works with esm
  4. Shebang (how to look like a real shell tool)
  5. Modifying errors before printing them
  6. Custom human friendly error output

Async main wrap

npm version Build Status Coverage Status

A simple utility to base cli tools on async methods.

// cli.js

const wrap = require("@gustavnikolaj/async-main-wrap");
const main = require("./main.js");

wrap(main)(process.cwd(), process.argv.slice(2));

// main.js

module.exports = async function cliTool(cwd, args) {
  if (!condition) {
    throw new Error("foo!"); // Will exit the CLI tool with status code 1.
  }

  console.log("All done!");
};

The motivation behind this tool is that I got tired of writing the same lines to wrap my main method for small cli utilities.

Besides being small and simple, this tool also makes testing your cli tool a lot simpler. You don't have to actually run it through the command line to test it, you can simply test your main method.

The following rules apply for main methods:

  • They should return a promise (or, you know, be an async function).
  • If they throw an error with a numeric exitCode property that will be used when shutting down the process.

There is examples in both the examples directory as well as in test/__fixtures__. The fixtures contains some examples of different use, but in general, most of it will look like the example at the top, and the best reference for a more real world implementation is most likely going to be the glob example.

Tips

Pass in your output channels

No clever things is done around what arguments you're passed. Whatever you pass to the wrapped method is passed on to your actual method. If you want to make testing the output easier, you can pass the console object to your method.

// cli.js

const wrap = require("@gustavnikolaj/async-main-wrap");
const main = require("./main.js");

wrap(main)(process.cwd(), process.argv.slice(2), console);

// main.js

module.exports = async function cliTool(args, console) {
  const name = args[0] || "world";

  console.log(`Hello, ${name}!`);
};

// main.spec.js

it("should say hello world", async () => {
  const logs = [];
  const mockConsole = {
    log(message) {
      logs.push(message);
    }
  };

  await main([], mockConsole);

  expect(logs, "to equal", ["Hello, world!"]);
});

it("should say hello Gustav", async () => {
  const logs = [];
  const mockConsole = {
    log(message) {
      logs.push(message);
    }
  };

  await main(["Gustav"], mockConsole);

  expect(logs, "to equal", ["Hello, Gustav!"]);
});

You could also pass in the raw process.stdout or process.stderr streams if you want tighter control.

Use with arguments parser

You can use any arguments parser you like, here I use yargs as an example:

// cli.js

const wrap = require("@gustavnikolaj/async-main-wrap");
const main = require("./main.js");

wrap(main)(process.cwd(), process.argv.slice(2));

// main.js

const yargs = require("yargs");

module.exports = async function main(cwd, args) {
  const argv = yargs(args).argv;

  if (argv.help) {
    printHelp();
    return;
  }

  // ...

  console.log("Done!");
};

Works with esm

The node "polyfill" for es modules: esm

// cli.js

require = require("esm")(module);
const wrap = require("@gustavnikolaj/async-main-wrap");
const main = require("./main").default;

wrap(main)(process.cwd(), process.argv.slice(2));

// main.js

export default async function main(cwd, args) {
  // ...
}

Shebang (how to look like a real shell tool)

The #! line at the top of the file will tell the shell how to execute the script, meaning that you no longer have to call the script with the node binary.

#!/usr/bin/env node

const wrap = require("@gustavnikolaj/async-main-wrap");
const main = require("./main.js");

wrap(main)(process.cwd(), process.argv.slice(2));

For this to work you need to give the script executable permissions. That can be done like this on Linux and Mac:

$ chmod +x my-awesome-tool

Modifying errors before printing them

Sometimes you will want to do something to your errors before printing them. E.g. the invariant module will throw errors with a custom property framesToPop that error handlers can use as a hint to remove frames from the stack trace - the module will put itself on top of any stack trace, because of how it functions. Using a module like frame-popper you can remove those extra stack frames.

#!/usr/bin/env node

const wrap = require("@gustavnikolaj/async-main-wrap");
const framePopper = require("@gustavnikolaj/frame-popper");
const main = require("./framePopper-main");

wrap(main, { processError: err => framePopper(err) })();

Custom human friendly error output

By setting a customOutput property on your errors you can override the output generated by async-main-wrap. Setting the DEBUG environment variable will disable customOutput-based output and print the full details.

Can be combined with the processError option to generate friendly errors for all your errors.

// main.js

module.exports = async function(/* ... */) {
  // ...

  const err = new Error("Such an unfriendly error message");
  err.customOutput = "So friendly, but still an error!";
  throw err;

  // ...
};
$ cli
So friendly, but still an error!

版本与发布记录

@gustavnikolaj/async-main-wrap 共发布 8 个版本,首次发布于 2018/06/07;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.0latest2021/07/265 年前
3.0.12019/02/197 年前
3.0.02018/08/228 年前
2.2.02018/08/228 年前
2.1.02018/08/218 年前
2.0.02018/07/158 年前

关于 @gustavnikolaj/async-main-wrap 的常见问题

@gustavnikolaj/async-main-wrap 是什么?

Simple CLI tool wrapper.

如何安装 @gustavnikolaj/async-main-wrap?

在项目目录运行 npm install @gustavnikolaj/async-main-wrap,或使用 pnpm add / yarn add / bun add。

@gustavnikolaj/async-main-wrap 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/gustavnikolaj__async-main-wrap 是否存在。

@gustavnikolaj/async-main-wrap 支持 ESM 还是 CommonJS?

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

@gustavnikolaj/async-main-wrap 可以商用吗?

@gustavnikolaj/async-main-wrap 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gustavnikolaj/async-main-wrap 的下载量有多少?

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

@gustavnikolaj/async-main-wrap 还在维护吗?

最新版本 4.0.0 发布于 2021/07/26(5 年前);至今共发布 8 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/06/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。