Appearance
常见问题
¥FAQ
传递环境变量
¥Passing env variables
js
process.env.FOO = 'bar'
await $`echo $FOO`
传递值数组
¥Passing array of values
当将值数组作为参数传递给 $
时,数组中的项目将单独转义并通过空格连接。
¥When passing an array of values as an argument to $
, items of the array will be escaped individually and concatenated via space.
示例:
¥Example:
js
const files = [...]
await $`tar cz ${files}`
导入到其他脚本中
¥Importing into other scripts
可以通过显式导入来使用 $
和其他函数:
¥It is possible to make use of $
and other functions via explicit imports:
js
#!/usr/bin/env node
import {$} from 'zx'
await $`date`
附加配置文件
¥Attaching a profile
默认情况下,child_process
不包含别名和 bash 函数。但你仍然可以手动完成。只需将必要的指令附加到 $.prefix
。
¥By default child_process
does not include aliases and bash functions. But you are still able to do it by hand. Just attach necessary directives to the $.prefix
.
js
$.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
await $`nvm -v`
使用 GitHub Actions
¥Using GitHub Actions
默认的 GitHub Action 运行器附带安装了 npx
。
¥The default GitHub Action runner comes with npx
installed.
yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
env:
FORCE_COLOR: 3
run: |
npx zx <<'EOF'
await $`...`
EOF
冗长且安静
¥Verbose and Quiet
zx 有内部日志器,如果满足条件,它会捕获事件:
¥zx has internal logger, which captures events if a condition is met:
事件 | 详细 | 安静 | 描述 |
---|---|---|---|
stdout | true | false | 生成的进程 stdout |
stderr | any | false | 处理 stderr 数据 |
cmd | true | false | 命令执行 |
fetch | true | false | 通过 http(s) 获取资源 |
cd | true | false | 更改目录 |
retry | true | false | 捕获执行错误 |
custom | true | false | 用户定义事件 |
默认情况下,$.verbose
和 $.quiet
选项都是 false
,因此只写入 stderr
事件。任何输出都会进入 process.stderr
流。
¥By default, both $.verbose
and $.quiet
options are false
, so only stderr
events are written. Any output goes to the process.stderr
stream.
你可以全局或就地控制此流程
¥You may control this flow globally or in-place
js
// Global debug mode on
$.verbose = true
await $`echo hello`
// Suppress the particular command
await $`echo fobar`.quiet()
// Suppress everything
$.quiet = true
await $`echo world`
// Turn on in-place debug
await $`echo foo`.verbose()
你还可以用自己的日志器覆盖默认日志器:
¥You can also override the default logger with your own:
js
// globally
$.log = (entry) => {
switch (entry.kind) {
case 'cmd':
console.log('Command:', entry.cmd)
break
default:
console.warn(entry)
}
}
// or in-place
$({log: () => {}})`echo hello`
Canary / Beta / RC 版本
¥Canary / Beta / RC builds
不耐烦的早期采用者可以尝试实验性的 zx 版本。但请记住:这些构建在任何意义上都是 ⚠️️__beta__ 。
¥Impatient early adopters can try the experimental zx versions. But keep in mind: these builds are ⚠️️__beta__ in every sense.
bash
npm i zx@dev
npx zx@dev --install --quiet <<< 'import _ from "lodash" /* 4.17.15 */; console.log(_.VERSION)'