# 馃悮 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}`
```
Bash is great, but when it comes to writing more complex scripts,
many people prefer a more convenient programming language.
JavaScript is a perfect choice, but the Node.js standard library
requires additional hassle before using. The `zx` package provides
useful wrappers around `child_process`, escapes arguments and
gives sensible defaults.
## Install
```bash
npm i -g zx
```
**Requirement**: Node version >= 16.0.0
## Goods
[$](#command-) 路 [cd()](#cd) 路 [fetch()](#fetch) 路 [question()](#question) 路 [sleep()](#sleep) 路 [echo()](#echo) 路 [stdin()](#stdin) 路 [within()](#within) 路 [retry()](#retry) 路 [spinner()](#spinner) 路
[chalk](#chalk-package) 路 [fs](#fs-package) 路 [os](#os-package) 路 [path](#path-package) 路 [glob](#globby-package) 路 [yaml](#yaml-package) 路 [minimist](#minimist-package) 路 [which](#which-package) 路
[__filename](#__filename--__dirname) 路 [__dirname](#__filename--__dirname) 路 [require()](#require)
For running commands on remote hosts,
see [webpod](https://github.com/webpod/webpod).
## Documentation
Write your scripts in a file with an `.mjs` extension in order to
use `await` at the top level. If you prefer the `.js` extension,
wrap your scripts in something like `void async function () {...}()`.
Add the following shebang to the beginning of your `zx` scripts:
```bash
#!/usr/bin/env zx
```
Now you will be able to run your script like so:
```bash
chmod +x ./script.mjs
./script.mjs
```
Or via the `zx` executable:
```bash
zx ./script.mjs
```
All functions (`$`, `cd`, `fetch`, etc) are available straight away
without any imports.
Or import globals explicitly (for better autocomplete in VS Code).
```js
import 'zx/globals'
```
### ``$`command` ``
Executes a given command using the `spawn` func
and returns [`ProcessPromise`](#processpromise).
Everything passed through `${...}` will be automatically escaped and quoted.
```js
let name = 'foo & bar'
await $`mkdir ${name}`
```
**There is no need to add extra quotes.** Read more about it in
[quotes](docs/quotes.md).
You can pass an array of arguments if needed:
```js
let flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`
```
If the executed program returns a non-zero exit code,
[`ProcessOutput`](#processoutput) will be thrown.
```js
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}
```
### `ProcessPromise`
```ts
class ProcessPromise extends Promise<ProcessOutput> {
stdin: Writable
stdout: Readable
stderr: Readable
exitCode: Promise<number>
pipe(dest): ProcessPromise
kill(): Promise<void>
nothrow(): this
quiet(): this
}
```
Read more about the [ProcessPromise](docs/process-promise.md).
### `ProcessOutput`
```ts
class ProcessOutput {
readonly stdout: string
readonly stderr: string
readonly signal: string
readonly exitCode: number
toString(): string // Combined stdout & stderr.
}
```
The output of the process is captured as-is. Usually, programs print a new
line `\n` at the end.
If `ProcessOutput` is used as an argument to some other `$` process,
**zx** will use stdout and trim the new line.
```js
let date = await $`date`
await $`echo Current date is ${date}.`
```
## Functions
### `cd()`
Changes the current working directory.
```js
cd('/tmp')
await $`pwd` // => /tmp
```
### `fetch()`
A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch)
package.
```js
let resp = await fetch('https://medv.io')
```
### `question()`
A wrapper around the [readline](https://nodejs.org/api/readline.html) package.
```js
let bear = await question('What kind of bear is best? ')
```
### `sleep()`
A wrapper around the `setTimeout` function.
```js
await sleep(1000)
```
### `echo()`
A `console.log()` alternative which can take [ProcessOutput](#processoutput).
```js
let branch = await $`git branch --show-current`
echo`Current branch is ${branch}.`
// or
echo('Current branch is', branch)
```
### `stdin()`
Returns the stdin as a string.
```js
let content = JSON.parse(await stdin())
```
### `within()`
Creates a new async context.
```js
await $`pwd` // => /home/path
within(async () => {
cd('/tmp')
setTimeout(async () => {
await $`pwd` // => /tmp
}, 1000)
})
await $`pwd` // => /home/path
```
```js
let version = await within(async () => {
$.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
await $`nvm use 16`
return $`node -v`
})
```
### `retry()`
Retries a callback for a few times. Will return after the first
successful attempt, or will throw after specifies attempts count.
```js
let p = await retry(10, () => $`curl https://medv.io`)
// With a specified delay between attempts.
let p = await retry(20, '1s', () => $`curl https://medv.io`)
// With an exponential backoff.
let p = await retry(30, expBackoff(), () => $`curl https://medv.io`)
```
### `spinner()`
Starts a simple CLI spinner.
```js
await spinner(() => $`long-running command`)
// With a message.
await spinner('working...', () => $`sleep 99`)
```
## Packages
The following packages are available without importing inside scripts.
### `chalk` package
The [chalk](https://www.npmjs.com/package/chalk) package.
```js
console.log(chalk.blue('Hello world!'))
```
### `fs` package
The [fs-extra](https://www.npmjs.com/package/fs-extra) package.
```js
let {version} = await fs.readJson('./package.json')
```
### `os` package
The [os](https://nodejs.org/api/os.html) package.
```js
await $`cd ${os.homedir()} && mkdir example`
```
### `path` package
The [path](https://nodejs.org/api/path.html) package.
```js
await $`mkdir ${path.join(basedir, 'output')}`
```
### `globby` package
The [globby](https://github.com/sindresorhus/globby) package.
```js
let packages = await glob(['package.json', 'packages/*/package.json'])
```
### `yaml` package
The [yaml](https://www.npmjs.com/package/yaml) package.
```js
console.log(YAML.parse('foo: bar').foo)
```
### `minimist` package
The [minimist](https://www.npmjs.com/package/minimist) package available
as global const `argv`.
```js
if (argv.someFlag) {
echo('yes')
}
```
### `which` package
The [which](https://github.com/npm/node-which) package.
```js
let node = await which('node')
```
## Configuration
### `$.shell`
Specifies what shell is used. Default is `which bash`.
```js
$.shell = '/usr/bin/bash'
```
Or use a CLI argument: `--shell=/bin/bash`
### `$.spawn`
Specifies a `spawn` api. Defaults to `require('child_process').spawn`.
### `$.prefix`
Specifies the command that will be prefixed to all commands run.
Default is `set -euo pipefail;`.
Or use a CLI argument: `--prefix='set -e;'`
### `$.quote`
Specifies a function for escaping special characters during
command substitution.
### `$.verbose`
Specifies verbosity. Default is `true`.
In verbose mode, `zx` prints all executed commands alongside with their
outputs.
Or use the CLI argument `--quiet` to set `$.verbose = false`.
### `$.env`
Specifies an environment variables map.
Defaults to `process.env`.
### `$.cwd`
Specifies a current working directory of all processes created with the `$`.
The [cd()](#cd) func changes only `process.cwd()` and if no `$.cwd` specified,
all `$` processes use `process.cwd()` by default (same as `spawn` behavior).
### `$.log`
Specifies a [logging function](src/core.ts).
```ts
import { LogEntry, log } from 'zx/core'
$.log = (entry: LogEntry) => {
switch (entry.kind) {
case 'cmd':
// for example, apply custom data masker for cmd printing
process.stderr.write(masker(entry.cmd))
break
default:
log(entry)
}
}
```
## Polyfills
### `__f
没有合适的资源?快使用搜索试试~ 我知道了~
编写更好脚本的工具___下载.zip
共65个文件
ts:14个
js:11个
md:10个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 136 浏览量
2023-04-19
00:41:47
上传
评论
收藏 169KB ZIP 举报
温馨提示
编写更好脚本的工具___下载.zip
资源推荐
资源详情
资源评论
收起资源包目录
编写更好脚本的工具___下载.zip (65个子文件)
zx-main
stryker.conf.json 343B
.github
pages
index.html 16B
ISSUE_TEMPLATE.md 130B
workflows
npm-publish.yml 434B
test.yml 786B
check.yml 808B
dev-publish.yml 633B
FUNDING.yml 18B
PULL_REQUEST_TEMPLATE.md 184B
src
experimental.ts 710B
goods.ts 5KB
deps.ts 3KB
core.ts 13KB
cli.ts 7KB
globals.ts 2KB
index.ts 1001B
repl.ts 1KB
util.ts 10KB
LICENSE 11KB
.nycrc 92B
examples
backup-github.mjs 1KB
interactive.mjs 1KB
background-process.mjs 792B
parallel.mjs 1002B
.prettierignore 96B
docs
contributing.md 1KB
quotes.md 1KB
known-issues.md 988B
process-promise.md 3KB
markdown.md 603B
code-of-conduct.md 4KB
package.json 2KB
package-lock.json 388KB
test-d
experimental.test-d.ts 622B
goods.test-d.ts 1KB
core.test-d.ts 2KB
globals.test-d.ts 922B
test
deps.test.js 3KB
experimental.test.js 750B
global.test.js 1KB
package.test.js 2KB
fixtures
ts-project
package.json 109B
script.ts 679B
tsconfig.json 222B
no-extension 783B
interactive.mjs 804B
argv.mjs 768B
require.mjs 749B
filename-dirname.mjs 737B
no-extension.mjs 668B
echo.http 116B
js-project
package.json 81B
script.js 607B
markdown.md 361B
exit-code.mjs 611B
core.test.js 11KB
extra.test.js 2KB
util.test.js 3KB
win32.test.js 1KB
goods.test.js 4KB
cli.test.js 6KB
.gitignore 116B
tsconfig.json 280B
README.md 12KB
tsconfig.prod.json 52B
共 65 条
- 1
资源评论
快撑死的鱼
- 粉丝: 1w+
- 资源: 9154
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 电子设计竞赛的单相不间断电源设计
- cutcamera1715961370938.png
- 基于MATLAB的图像处理课程设计报告.doc
- tensorflow-gpu-2.6.0-cp38-cp38-manylinux2010-x86-64.whl
- mmexport1715960553858.png
- tensorflow-gpu-2.6.0-cp37-cp37m-manylinux2010-x86-64.whl
- 通过 .NET 应用程序中的源代码查找 SQL 注入
- 电子设计竞赛2007年B题 无线识别装置.doc
- Wox全局搜索工具,一款win下的全局搜索软件
- 使用高级集群管理 (ACM) 模板来管理用户、组和命名空间
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功