🐚 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
许可证
免责声明: 这不是官方支持的Google产品.