跳到内容

API 参考

$.sync

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

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

$({...})

$ 对象持有默认的 zx 配置,用于所有执行。要指定自定义预设,请将 $ 用作工厂

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!"`

此外,预设是可链接的

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})

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

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})

signal 选项使进程可中止。

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

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

$({timeout})

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

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

$({nothrow})

nothrow 选项抑制错误并返回带有详细信息的 ProcessOutput

js
const o1 = await $({nothrow: true})`exit 1`
o1.ok       // false
o1.exitCode // 1
o1.message  // exit code: 1 ...

const o2 = await $({nothrow: true, spawn() { throw new Error('BrokenSpawn') }})`echo foo`
o2.ok       // false
o2.exitCode // null
o2.message  // BrokenSpawn ...

完整的选项列表

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

另请参见 配置

cd()

更改当前工作目录。

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

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

js
cd(await $`mktemp -d`)

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

fetch()

围绕 node-fetch-native 包的包装器。

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

在某些情况下,text()json() 可能会产生非常大的输出,超过字符串大小限制。流就是为此而生的,因此我们对 fetch API 进行了微小的调整,使其更易于管道操作。

js
const p1 = fetch('https://example.com').pipe($`cat`)
const p2 = fetch('https://example.com').pipe`cat`

question()

围绕 readline API 的包装器。

js
const bear = await question('What kind of bear is best? ')
const selected = await question('Select an option:', {
  choices: ['A', 'B', 'C'],
})

sleep()

围绕 setTimeout 函数的包装器。

js
await sleep(1000)

echo()

console.log() 的替代方案,可以接受 ProcessOutput

js
const branch = await $`git branch --show-current`

echo`Current branch is ${branch}.`
// or
echo('Current branch is', branch)

stdin()

将 stdin 作为字符串返回。

js
const content = JSON.parse(await stdin())

within()

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

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() 与之同步。

ts
import {syncProcessCwd} from 'zx'

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

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

retry()

重试一个回调函数几次。在第一次尝试成功后返回,或在指定的尝试次数后抛出异常。

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 spinner。

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

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

默认情况下,对于 CI 禁用它。

glob()

globby 包。

js
const packages = await glob(['package.json', 'packages/*/package.json'])
const markdowns = glob.sync('*.md') // sync API shortcut

which()

which 包。

js
const node = await which('node')

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

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

ps

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

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()

一个进程杀手。

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

tmpdir()

创建一个临时目录。

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

tmpfile()

临时文件工厂。

js
f1 = tmpfile()         // /os/based/tmp/zx-1ra1iofojgg
f2 = tmpfile('f2.txt')  // /os/based/tmp/zx-1ra1iofojgg/foo.txt
f3 = tmpfile('f3.txt', 'string or buffer')
f4 = tmpfile('f4.sh', 'echo "foo"', 0o744) // executable

minimist

minimist 包。

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

argv

作为 argvprocess.argv 的 minimist 解析版本。

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

使用 minimist 选项来自定义解析

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

chalk

chalk 包。

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

fs

fs-extra 包。

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

os

os 包。

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

path

path 包。

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

yaml

yaml 包。

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

dotenv

envapi 包。
一个与 dotenv 格式的环境变量交互的 API。

js
// parse
const raw = 'FOO=BAR\nBAZ=QUX'
const data = dotenv.parse(raw) // {FOO: 'BAR', BAZ: 'QUX'}
await fs.writeFile('.env', raw)

// load
const env = dotenv.load('.env')
await $({ env })`echo $FOO`.stdout // BAR

// config
dotenv.config('.env')
process.env.FOO // BAR

quote()

默认 bash 引用函数。

js
quote("$FOO") // "$'$FOO'"

quotePowerShell()

PowerShell 特定的引用。

js
quotePowerShell("$FOO") // "'$FOO'"

useBash()

启用 bash 预设:设置 $.shellbash$.quotequote

js
useBash()

usePowerShell()

切换到 PowerShell。应用 quotePowerShell 进行引用。

js
usePowerShell()

usePwsh()

设置 pwsh (PowerShell v7+) 作为 $.shell 默认值。

js
usePwsh()

免责声明:这不是 Google 官方支持的产品。