开始使用
概述
js
#!/usr/bin/env zx
await $`cat package.json | grep name`
const 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`,
])
const name = 'foo bar'
await $`mkdir /tmp/${name}`
Bash 很棒,但当编写更复杂的脚本时,许多人更喜欢更方便的编程语言。 JavaScript 是一个完美的选择,但 Node.js 标准库在使用前需要额外的麻烦。 zx
包提供了围绕 child_process
的有用包装器,转义参数并提供合理的默认值。
安装
bash
npm install zx
或许多其他方法
用法
以 .mjs
扩展名将脚本写入文件,以便在顶层使用 await
。 如果您更喜欢 .js
扩展名,请将您的脚本包装在类似 void async function () {...}()
的东西中。
将以下 shebang 添加到您的 zx
脚本的开头
bash
#!/usr/bin/env zx
现在您将能够像这样运行您的脚本
bash
chmod +x ./script.mjs
./script.mjs
或通过 CLI
bash
zx ./script.mjs
所有函数($
、cd
、fetch
等)都可以直接使用,无需任何导入。
或显式导入全局变量(以便在 VS Code 中获得更好的自动完成功能)。
js
import 'zx/globals'
$`command`
使用 spawn
函数执行给定的命令,并返回 ProcessPromise
。 它支持同步和异步模式。
js
const list = await $`ls -la`
const dir = $.sync`pwd`
所有通过 ${...}
传递的内容都将自动转义并用引号引起来。
js
const name = 'foo & bar'
await $`mkdir ${name}`
无需添加额外的引号。 在引号中阅读更多相关信息。
如果需要,您可以传递一个参数数组
js
const flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`
如果执行的程序返回非零退出代码,则会抛出 ProcessOutput
。
js
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}
ProcessOutput
ts
class ProcessOutput {
readonly stdout: string
readonly stderr: string
readonly signal: string
readonly exitCode: number
toString(): string // Combined stdout & stderr.
}
进程的输出按原样捕获。 通常,程序在末尾打印一个新行 \n
。 如果 ProcessOutput
用作某些其他 $
进程的参数,zx 将使用 stdout 并修剪新行。
js
const date = await $`date`
await $`echo Current date is ${date}.`
许可证
免责声明:这不是 Google 官方支持的产品。