Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

备稿计划: 使用 deno 制作 CLI 工具最佳实践 (草稿) #175

Open
iugo opened this issue Jan 15, 2025 · 0 comments
Open

备稿计划: 使用 deno 制作 CLI 工具最佳实践 (草稿) #175

iugo opened this issue Jan 15, 2025 · 0 comments
Assignees

Comments

@iugo
Copy link
Member

iugo commented Jan 15, 2025

直接运行

在第一行增加 #!/usr/bin/env -S deno run --allow-all 即可.

注意文件需要可执行权限, 使用 chmod +x {file_path} 增加可执行权限.

读取参数

命令行工具的主要特点就是可以获取参数. 可以使用 Deno.args 获取.

使用标准库

使用标准库可以避免重复造轮子, 节约我们的时间. Deno 关于命令行工具的标准库在: https://jsr.io/@std/cli

parseArgs

解析的例子如:

[ "pre", "-A", "--b=c", "--de", "fg", "post" ] // 输入
{ _: [ "pre", "post" ], A: true, b: "c", de: "fg" } // 输出

错误处理

对于命令行程序来说, 遇到预期中的错误可以使用 Deno.exit(1) 退出, 而不是抛错.

打印信息着色

可以使用 Web API, 文档为: https://developer.mozilla.org/en-US/docs/Web/API/console#styling_console_output

比如:

const CSS_STYLE_ERROR = 'color: red; font-style: italic; padding: 2px';
const CSS_STYLE_EMPTY = '';

console.error(
  '%cerr:%c message',
  CSS_STYLE_ERROR,
  CSS_STYLE_EMPTY,
);
@iugo iugo self-assigned this Jan 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant