Skip to content

API 参考

¥API Reference

$.sync

Zx 提供同步和异步命令执行,分别返回 ProcessOutputProcessPromise

¥Zx provides both synchronous and asynchronous command executions, returns ProcessOutput or ProcessPromise respectively.

js
const list = await $`ls -la`
const dir = $.sync`pwd`

$({...}) {#}

$ 对象保存默认的 zx configuration,用于所有执行。要指定自定义预设,请使用 $ 作为工厂:

¥$ object holds the default zx configuration, which is used for all execution. To specify a custom preset use $ as factory:

js
const $$ = $({
  verbose: false,
  env: {NODE_ENV: 'production'},
})

const env = await $$`node -e 'console.log(process.env.NODE_ENV)'`
const pwd = $$.sync`pwd`
const hello = $({quiet: true})`echo "Hello!"`

此外,预设是可链式的:

¥Moreover, presets are chainable:

js
const $1 = $({ nothrow: true })
assert.equal((await $1`exit 1`).exitCode, 1)

const $2 = $1({ sync: true }) // Both {nothrow: true, sync: true} are applied
assert.equal($2`exit 2`.exitCode, 2)

const $3 = $({ sync: true })({ nothrow: true })
assert.equal($3`exit 3`.exitCode, 3)

$({input})

输入选项将指定的 stdin 传递给命令。

¥The input option passes the specified stdin to the command.

js
const p1 = $({ input: 'foo' })`cat`
const p2 = $({ input: Readable.from('bar') })`cat`
const p3 = $({ input: Buffer.from('baz') })`cat`
const p4 = $({ input: p3 })`cat`
const p5 = $({ input: await p3 })`cat`

$({signal})

信号选项使进程可中止。

¥The signal option makes the process abortable.

js
const {signal} = new AbortController()
const p = $({ signal })`sleep 9999`

setTimeout(() => signal.abort('reason'), 1000)

$({timeout})

超时选项使进程在指定的延迟后可自动终止。

¥The timeout option makes the process autokillable after the specified delay.

js
const p = $({timeout: '1s'})`sleep 999`

完整选项列表:

¥The full options list:

ts
interface Options {
  cwd:            string
  ac:             AbortController
  signal:         AbortSignal
  input:          string | Buffer | Readable | ProcessOutput | ProcessPromise
  timeout:        Duration
  timeoutSignal:  string
  stdio:          StdioOptions
  verbose:        boolean
  sync:           boolean
  env:            NodeJS.ProcessEnv
  shell:          string | boolean
  nothrow:        boolean
  prefix:         string
  postfix:        string
  quote:          typeof quote
  quiet:          boolean
  detached:       boolean
  spawn:          typeof spawn
  spawnSync:      typeof spawnSync
  log:            typeof log
  kill:           typeof kill
}

cd()

更改当前工作目录。

¥Changes the current working directory.

js
cd('/tmp')
await $`pwd` // => /tmp

echo 一样,除了 string 参数之外,cd 还接受并修剪 ProcessOutput 中的尾随换行符,从而实现常见的习惯用法,例如:

¥Like echo, in addition to string arguments, cd accepts and trims trailing newlines from ProcessOutput enabling common idioms like:

js
cd(await $`mktemp -d`)

⚠️ cd 在内部调用 process.chdir(),因此它确实会影响全局上下文。要使 process.cwd() 与单独的 $ 调用保持同步,请启用 syncProcessCwd() 钩子。

¥⚠️ cd invokes process.chdir() internally, so it does affect the global context. To keep process.cwd() in sync with separate $ calls enable syncProcessCwd() hook.

fetch()

node-fetch-native 封装的封装纸。

¥A wrapper around the node-fetch-native package.

js
const resp = await fetch('https://medv.io')

question()

readline 封装的封装纸。

¥A wrapper around the readline package.

js
const bear = await question('What kind of bear is best? ')

sleep()

setTimeout 函数的封装器。

¥A wrapper around the setTimeout function.

js
await sleep(1000)

echo()

可以采用 ProcessOutputconsole.log() 替代方案。

¥A console.log() alternative which can take ProcessOutput.

js
const 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
const content = JSON.parse(await stdin())

within()

创建一个新的异步上下文。

¥Creates a new async context.

js
await $`pwd` // => /home/path
$.foo = 'bar'

within(async () => {
  $.cwd = '/tmp'
  $.foo = 'baz'

  setTimeout(async () => {
    await $`pwd` // => /tmp
    $.foo // baz
  }, 1000)
})

await $`pwd` // => /home/path
$.foo // still 'bar'
js
await $`node --version` // => v20.2.0

const version = await within(async () => {
  $.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; nvm use 16;'

  return $`node --version`
})

echo(version) // => v16.20.0

syncProcessCwd()

如果通过 cd() 更改,则使 process.cwd() 与内部 $ 当前工作目录保持同步。

¥Keeps the process.cwd() in sync with the internal $ current working directory if it is changed via cd().

ts
import {syncProcessCwd} from 'zx'

syncProcessCwd()
syncProcessCwd(false) // pass false to disable the hook

由于性能开销,默认情况下禁用此功能。

¥This feature is disabled by default because of performance overhead.

retry()

重试回调几次。将在第一次成功尝试后返回,或者在指定尝试次数后抛出。

¥Retries a callback for a few times. Will return after the first successful attempt, or will throw after specifies attempts count.

js
const p = await retry(10, () => $`curl https://medv.io`)

// With a specified delay between attempts.
const p = await retry(20, '1s', () => $`curl https://medv.io`)

// With an exponential backoff.
const p = await retry(30, expBackoff(), () => $`curl https://medv.io`)

spinner()

启动一个简单的 CLI 加载控件。

¥Starts a simple CLI spinner.

js
await spinner(() => $`long-running command`)

// With a message.
await spinner('working...', () => $`sleep 99`)

glob()

globby 包。

¥The globby package.

js
const packages = await glob(['package.json', 'packages/*/package.json'])

which()

which 包。

¥The which package.

js
const node = await which('node')

如果使用 nothrow 选项,则在未找到时返回 null。

¥If nothrow option is used, returns null if not found.

js
const pathOrNull = await which('node', { nothrow: true })

ps()

@webpod/ps 包提供了一种跨平台的方式来列出进程。

¥The @webpod/ps package to provide a cross-platform way to list processes.

js
const all = await ps.lookup()
const nodejs = await ps.lookup({ command: 'node' })
const children = await ps.tree({ pid: 123 })
const fulltree = await ps.tree({ pid: 123, recursive: true })

kill()

进程杀手。

¥A process killer.

js
await kill(123)
await kill(123, 'SIGKILL')

tmpdir()

创建一个临时目录。

¥Creates a temporary directory.

js
t1 = tmpdir()       // /os/based/tmp/zx-1ra1iofojgg/
t2 = tmpdir('foo')  // /os/based/tmp/zx-1ra1iofojgg/foo/

tmpfile()

临时文件工厂。

¥Temp file factory.

js
f1 = tmpfile()         // /os/based/tmp/zx-1ra1iofojgg
f2 = tmpfile('f.txt')  // /os/based/tmp/zx-1ra1iofojgg/foo.txt
f3 = tmpfile('f.txt', 'string or buffer')

minimist

minimist 包。

¥The minimist package.

js
const argv = minimist(process.argv.slice(2), {})

argv

process.argv 的简约解析版本为 argv

¥A minimist-parsed version of the process.argv as argv.

js
if (argv.someFlag) {
  echo('yes')
}

使用 minimist 选项来自定义解析:

¥Use minimist options to customize the parsing:

js
const myCustomArgv = minimist(process.argv.slice(2), {
  boolean: [
    'force',
    'help',
  ],
  alias: {
    h: 'help',
  },
})

chalk

chalk 包。

¥The chalk package.

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

fs

fs-extra 包。

¥The fs-extra package.

js
const {version} = await fs.readJson('./package.json')

os

os 包。

¥The os package.

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

path

path 包。

¥The path package.

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

yaml

yaml 包。

¥The yaml package.

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

google/zx 中文网 - 粤ICP备13048890号