@cspotcode/zx

中文文档
6.1.2发布于 2022/07/04Apache-2.0TypeScriptESM + CJS近 30 天下载 6562

一个写得更好的脚本的工具.

中文使用文档
文档目录50 节
  1. 安装
  2. 货物
  3. 文档
  4. $`command`
  5. ProcessPromise
  6. ProcessOutput
  7. 职能
  8. cd()
  9. fetch()
  10. question()
  11. sleep()
  12. nothrow()
  13. quiet()
  14. 软件包
  15. chalk 软件包
  16. fs 软件包
  17. os 软件包
  18. path 软件包
  19. globby 软件包
  20. yaml 软件包
  21. minimist 软件包
  22. which 软件包
  23. 配置
  24. $.shell
  25. $.spawn
  26. $.maxBuffer
  27. $.prefix
  28. $.quote
  29. $.verbose
  30. 圆柱体
  31. __filename 打开 __dirname
  32. require()
  33. 实验
  34. retry()
  35. echo()
  36. startSpinner()
  37. withTimeout()
  38. 财务问题
  39. 传递内存变量
  40. 传递数组
  41. 从其他脚本导入
  42. 没有扩展的脚本
  43. 标记下脚本
  44. 类型脚本
  45. 执行远程脚本
  46. 从 stdin 执行脚本
  47. 附图.bash profile/.zshrc
  48. 使用 GitHub 动作
  49. 自定义
  50. 许可证

🐚 zx

叉子为 zx 在共同JS的支持下.

#!/usr/bin/env zx

await $`cat package.json | grep name`

let branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`

await Promise.all([
  $`sleep 1; echo 1`,
  $`sleep 2; echo 2`,
  $`sleep 3; echo 3`,
])

let name = 'foo bar'
await $`mkdir /tmp/${name}`

巴什很棒 但写剧本时, 人们通常选择更方便的编程语言. JavaScript 是一个完美的选择, 但标准节点.js 库 使用前需要额外的麻烦。 这个 zx 软件包提供 围绕有用的包装 child_process,以逃避争论和 给予合理的默认.

安装

npm i -g @cspotcode/zx

所需经费:节点版QQ 16.0.0

货物

(单位:美元) • 妇女 cd () (中文(简体) ) • 妇女 获取( c) • 妇女 问题() • 妇女 睡眠( ) • 妇女 无编号( ) • 妇女 静( ) • 妇女 粉笔 • 妇女 小时 • 妇女 单位 • 妇女 路径 • 妇女 荣耀 • 妇女 雅姆尔 • 妇女 最小数 • 妇女 哪个 • 妇女 文件名 • 妇女 目录 • 妇女 要求( )

文档

在文件中写入脚本 .mjs 扩展至 能够使用 await 在顶层。 如果你喜欢 .js 扩展, 将脚本包成类似的东西 void async function () {...}()。 。 。 .

在您的起始处添加以下 shebang zx 脚本 :

#!/usr/bin/env zx

现在你可以这样运行你的剧本:

chmod +x ./script.mjs
./script.mjs

或者通过 zx 可执行文件 :

zx ./script.mjs

所有职能$, (中文(简体) ), cd, (中文(简体) ), fetch(等等)可立即提供 没有任何进口.

或明确导入全局( 用于在 VS 代码中更好地自动完成) .

import '@cspotcode/zx/globals'

$`command`

使用 spawn 函数从 child_process 软件包和返回 ProcessPromise<ProcessOutput>。 。 。 .

一切经过 ${...} 将被自动逃脱并引用.

let name = 'foo & bar'
await $`mkdir ${name}`

不必多加引语. 更多关于它的 引用。 。 。 .

如果需要, 您可以通过一系列参数 :

let flags = [
  '--oneline',
  '--decorate',
  '--color',
]
await $`git log ${flags}`

如果执行的程序返回一个非零退出代码, ProcessOutput 将会被扔出.

try {
  await $`exit 1`
} catch (p) {
  console.log(`Exit code: ${p.exitCode}`)
  console.log(`Error: ${p.stderr}`)
}

ProcessPromise

class ProcessPromise<T> extends Promise<T> {
  readonly stdin: Writable
  readonly stdout: Readable
  readonly stderr: Readable
  readonly exitCode: Promise<number>
  pipe(dest): ProcessPromise<T>
  kill(signal = 'SIGTERM'): Promise<void>
}

这个 pipe() 用于重定向 stdout 的方法 :

await $`cat file.txt`.pipe(process.stdout)

更多信息 管道。 。 。 .

ProcessOutput

class ProcessOutput {
  readonly stdout: string
  readonly stderr: string
  readonly exitCode: number
  readonly signal: 'SIGTERM' | 'SIGKILL' | ...
  toString(): string
}

职能

cd()

更改当前工作目录 .

cd('/tmp')
await $`pwd` // outputs /tmp

fetch()

一个包裹环绕 节点比对 软件包.

let resp = await fetch('https://wttr.in')
if (resp.ok) {
  console.log(await resp.text())
}

question()

一个包裹环绕 已读行 软件包.

用法 :

let bear = await question('What kind of bear is best? ')
let token = await question('Choose env variable: ', {
  choices: Object.keys(process.env)
})

在第二个参数中,可以指定 Tab 自动补全的一系列选项 .

function question(query?: string, options?: QuestionOptions): Promise<string>
type QuestionOptions = { choices: string[] }

sleep()

一个包裹环绕 setTimeout 函数.

await sleep(1000)

nothrow()

改变行为 $ 避免对非零退出代码设置例外.

function nothrow<P>(p: P): P

用法 :

await nothrow($`grep something from-file`)

// Inside a pipe():

await $`find ./examples -type f -print0`
  .pipe(nothrow($`xargs -0 grep something`))
  .pipe($`wc -l`)

如果 exitCode 您可以使用下一个代码:

if (await $`[[ -d path ]]`.exitCode == 0) {
  ...
}

// Equivalent of:

if ((await nothrow($`[[ -d path ]]`)).exitCode == 0) {
  ...
}

quiet()

改变行为 $ 以禁用动词输出.

function quiet<P>(p: P): P

用法 :

await quiet($`grep something from-file`)
// Command and output will not be displayed.

软件包

后面的软件包是可用的,不导入内部脚本.

chalk 软件包

这个 粉笔 软件包.

console.log(chalk.blue('Hello world!'))

fs 软件包

这个 超时 软件包.

let content = await fs.readFile('./package.json')

os 软件包

这个 单位 软件包.

await $`cd ${os.homedir()} && mkdir example`

path 软件包

这个 路径 软件包.

await $`mkdir ${path.join(basedir, 'output')}`

globby 软件包

这个 荣耀 软件包.

let packages = await globby(['package.json', 'packages/*/package.json'])

let pictures = globby.globbySync('content/*.(jpg|png)')

另外,还有光荣通过 glob 快捷键 :

await $`svgo ${await glob('*.svg')}`

yaml 软件包

这个 雅姆尔 软件包.

console.log(YAML.parse('foo: bar').foo)

minimist 软件包

这个 最小数 软件包.

以全球连锁方式提供 argv。 。 。 .

which 软件包

这个 哪个 软件包.

let node = await which('node')

let node = which.sync('node')

配置

$.shell

指定所使用的 shell 。 默认是 which bash。 。 。 .

$.shell = '/usr/bin/bash'

或用 CLI 参数: --shell=/bin/bash

$.spawn

指定一个 spawn api. (英语). 默认为 require('child_process').spawn。 。 。 .

$.maxBuffer

指定在 stdout 或 stderr 上允许的最大字节数. 默认为 200 * 1024 * 1024 (200 MiB) (英语).

$.prefix

指定所有运行的命令的前缀命令.

默认是 set -euo pipefail;。 。 。 .

或用 CLI 参数: --prefix='set -e;'

$.quote

指定一个函数,用于在 命令替换.

$.verbose

指定动词。 默认是 true。 。 。 .

在动词模式下 zx 打印所有已执行的命令及其 产出.

或使用 CLI 参数 --quiet 设置 $.verbose = false。 。 。 .

圆柱体

__filename 打开 __dirname

单位 无害环境管理 模块,节点.js不提供 __filename 财务报告和审定财务报表 __dirname 环球网. 由于这样的全球 在脚本上真的很方便, zx 提供用于 .mjs 文件( 当使用 zx 可执行文件).

require()

单位 无害环境管理 模块 require() 未定义函数. 这个 zx 提供 require() 函数,因此可用于导入 .mjs 文件( 当使用时) zx 可执行文件).

let {version} = require('./package.json')

实验

Zx还提供了一些实验功能. 请留言 这些特征在 讨论情况。 。 。 . 通过 CLI 通道启用新功能 --experimental 旗帜.

retry()

复授一令数下. 第一次会回来的 成功尝试,或在指定尝试后投出.

import {retry} from '@cspotcode/zx/experimental'

let {stdout} = await retry(5)`curl localhost`

// with a specified delay between attempts
let {stdout} = await retry(3, 500)`npm whoami`

echo()

A 类 console.log() 可选择的选项 加工产出。 。 。 .

import {echo} from '@cspotcode/zx/experimental'

let branch = await $`git branch --show-current`

echo`Current branch is ${branch}.`
// or
echo('Current branch is', branch)

startSpinner()

启动简单的 CLI 旋转器,然后返回 stop() 函数.

import {startSpinner} from '@cspotcode/zx/experimental'

let stop = startSpinner()
await $`long-running command`
stop()

withTimeout()

运行并设定一个 cmd 的超时 .

import {withTimeout} from '@cspotcode/zx/experimental'

await withTimeout(100, 'SIGTERM')`sleep 9999`

财务问题

传递内存变量

process.env.FOO = 'bar'
await $`echo $FOO`

传递数组

如果数组作为参数传递到 $,该阵列中的项目将逃脱 通过空间单独和装饰.

示例

let files = [...]
await $`tar cz ${files}`

从其他脚本导入

可以利用 $ 通过明确进口实现其他功能:

#!/usr/bin/env node
import {$} from '@cspotcode/zx'
await $`date`

没有扩展的脚本

如果脚本没有文件扩展名( 如 : .git/hooks/pre-commit),zx (中文(简体) ) 假设这是一个 无害环境管理 模块.

标记下脚本

这个 zx 能够执行以下标写的脚本 (单位:千美元)文档/马克下.md:

zx docs/markdown.md

类型脚本

import {$} from '@cspotcode/zx'
// Or 
import '@cspotcode/zx/globals'

void async function () {
  await $`ls -la`
}()

使用 ts-节点 作为 一个埃斯姆节点 装填器。 。 。 .

node --loader ts-node/esm script.ts

你必须准备好 "type": "module" 内 package.json 财务报告和审定财务报表 "module": "ESNext" 内 tsconfig.json。 。 。 .

{
  "type": "module"
}
{
  "compilerOptions": {
    "module": "ESNext"
  }
}

执行远程脚本

如果争论到 zx 可执行文件起始于 https://,文件将 下载并执行.

zx https://medv.io/game-of-life.js

从 stdin 执行脚本

这个 zx 支持从 stdin 执行脚本.

zx <<'EOF'
await $`pwd`
EOF

附图.bash profile/.zshrc

默认 child_process 不包括别名和bash功能. 但你还是能用手来做 只要附上必要的指令 $.prefix。 。 。 .

$.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
await $`nvm -v`

使用 GitHub 动作

默认 GitHub 动作跑取器会安装 npx .

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3

    - name: Build
      env:
        FORCE_COLOR: 3
      run: |
        npx zx <<'EOF'
        await $`...`
        EOF

自定义

你可以自己打造最适合自己需要的自定义 zx 版本.

// index.js
import {$} from '@cspotcode/zx'

$.quote = () => {}
$.extraFn = async () => {
    await $`ping example.com`
    await $`npm whoami`
}

// cli.js
#!/usr/bin/env node

import './index.js'
import '@cspotcode/zx/cli'

// script.mjs
await $.extraFn()

// zx-custom script.mjs

许可证

阿帕奇 - 2.0

免责声明: 这不是官方支持的Google产品.

版本与发布记录

@cspotcode/zx 共发布 8 个版本,首次发布于 2021/08/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
6.1.2latest2022/07/044 年前
6.1.12022/07/044 年前
6.1.02022/05/214 年前
5.0.32022/02/114 年前
5.0.22022/02/114 年前
5.0.12022/02/104 年前

关于 @cspotcode/zx 的常见问题

@cspotcode/zx 是什么?

一个写得更好的脚本的工具.

如何安装 @cspotcode/zx?

在项目目录运行 npm install @cspotcode/zx,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 zx,可以用 npx zx 直接运行。

@cspotcode/zx 支持 TypeScript 吗?

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

@cspotcode/zx 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cspotcode/zx 需要什么版本的 Node.js?

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

@cspotcode/zx 可以商用吗?

@cspotcode/zx 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cspotcode/zx 的下载量有多少?

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

@cspotcode/zx 还在维护吗?

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