google-zx-scripting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google ZX Scripting

Google ZX 脚本编写

Use this skill when writing scripts with Google's
zx
library — the tool that makes shell scripting with JavaScript/TypeScript productive and safe. Read only the reference file(s) needed for the task.
当你使用Google的
zx
库编写脚本时可以使用本技能——zx是一款让JavaScript/TypeScript编写Shell脚本高效且安全的工具。仅阅读完成任务所需的参考文件即可。

Quick Start

快速开始

All zx scripts use the lite entry point for portability. Scripts are standalone
.mjs
files — no project setup required.
#!/usr/bin/env npx zx

import { $, fs, path, glob, chalk } from 'zx/core';

const files = await glob('src/**/*.ts');
await $`eslint ${files}`;
Run directly:
chmod +x script.mjs && ./script.mjs
# or
npx zx script.mjs
所有zx脚本都使用lite入口以保证可移植性。脚本是独立的
.mjs
文件——无需项目配置。
#!/usr/bin/env npx zx

import { $, fs, path, glob, chalk } from 'zx/core';

const files = await glob('src/**/*.ts');
await $`eslint ${files}`;
直接运行:
chmod +x script.mjs && ./script.mjs
# 或者
npx zx script.mjs

Critical Rules

重要规则

  1. Always use
    zx/core
    — import from
    zx/core
    (the lite bundle), never bare
    zx
    . This avoids the heavy CLI wrapper and keeps scripts lean and embeddable.
  2. Template literals auto-escape — interpolated values in
    $`...`
    are automatically shell-quoted. Never manually quote interpolated variables:
    $`echo ${userInput}`
    is safe,
    $`echo "${userInput}"`
    double-quotes and may break.
  3. Arrays expand correctly
    $`cmd ${arrayOfArgs}`
    expands each element as a separate quoted argument. Use this for flags, file lists, etc.
  4. Non-zero exits throw — by default, a failed command throws
    ProcessOutput
    as an error. Use
    nothrow
    option or
    .nothrow()
    to suppress when you expect failures (e.g.,
    grep
    returning no matches).
  5. Use
    within()
    for isolation
    within()
    creates an async scope with its own
    $.cwd
    ,
    $.env
    , and other settings. Essential for parallel tasks that need different working directories.
  6. Pipe with
    .pipe()
    — use
    $`cmd1`.pipe($`cmd2`)
    instead of shell pipes. This keeps each process managed by zx.
  7. Prefer zx builtins over shell commands — use
    glob()
    instead of
    find
    ,
    fs
    instead of
    cat
    /
    cp
    /
    mv
    ,
    fetch()
    instead of
    curl
    . These are cross-platform and return proper JS types.
  8. cd()
    is global
    cd()
    changes
    $.cwd
    for ALL subsequent commands. Use
    within()
    or
    $({cwd: '/path'})
    for scoped directory changes.
  9. Scripts must be
    .mjs
    — use
    .mjs
    extension for top-level
    await
    support without bundler config.
  1. 始终使用
    zx/core
    —— 从
    zx/core
    (轻量包)导入,绝不要直接导入
    zx
    。这样可以避免庞大的CLI包装器,保持脚本精简且可嵌入。
  2. 模板字面量自动转义 ——
    $`...`
    中的插值变量会自动进行Shell转义。绝不要手动为插值变量添加引号:
    $`echo ${userInput}`
    是安全的,而
    $`echo "${userInput}"`
    会添加双引号,可能导致脚本出错。
  3. 数组正确展开 ——
    $`cmd ${arrayOfArgs}`
    会将数组中的每个元素展开为单独的带引号参数。可用于标志、文件列表等场景。
  4. 非零退出码会抛出异常 —— 默认情况下,执行失败的命令会抛出
    ProcessOutput
    错误。当你预期会出现失败(例如
    grep
    未匹配到内容)时,使用
    nothrow
    选项或
    .nothrow()
    来抑制异常。
  5. 使用
    within()
    实现隔离
    ——
    within()
    会创建一个异步作用域,拥有独立的
    $.cwd
    $.env
    和其他设置。对于需要不同工作目录的并行任务来说至关重要。
  6. 使用
    .pipe()
    实现管道
    —— 使用
    $`cmd1`.pipe($`cmd2`)
    替代Shell管道。这样可以让每个进程都由zx管理。
  7. 优先使用zx内置工具而非Shell命令 —— 使用
    glob()
    替代
    find
    ,使用
    fs
    替代
    cat
    /
    cp
    /
    mv
    ,使用
    fetch()
    替代
    curl
    。这些工具是跨平台的,并且会返回标准的JS类型。
  8. cd()
    是全局的
    ——
    cd()
    会修改所有后续命令的
    $.cwd
    。如果需要作用域内的目录切换,请使用
    within()
    $({cwd: '/path'})
  9. 脚本必须为
    .mjs
    格式
    —— 使用
    .mjs
    扩展名以支持顶级
    await
    ,无需打包器配置。

Reference Map

参考映射

NeedFile
$
, ProcessPromise, ProcessOutput, configuration, piping, streams
references/core-api.md
Ad-hoc scripts, CLI tools, build scripts, deployment, project scaffolding
references/scripting-patterns.md
File processing, data pipelines, batch ops, AI scripts, log analysis
references/processing-recipes.md
需求文件
$
、ProcessPromise、ProcessOutput、配置、管道、流
references/core-api.md
临时脚本、CLI工具、构建脚本、部署、项目脚手架
references/scripting-patterns.md
文件处理、数据管道、批处理操作、AI脚本、日志分析
references/processing-recipes.md

Task Routing

任务路由

  • Writing a quick one-off command or shell automation ->
    references/scripting-patterns.md
  • Building a build/deploy/CI script ->
    references/scripting-patterns.md
  • Processing files, data, logs, or batch operations ->
    references/processing-recipes.md
  • Need API details for
    $
    , pipes, streams, config ->
    references/core-api.md
  • Combining multiple patterns (e.g., build + process) -> read both relevant files
  • 编写快速的一次性命令或Shell自动化脚本 ->
    references/scripting-patterns.md
  • 构建构建/部署/CI脚本 ->
    references/scripting-patterns.md
  • 处理文件、数据、日志或批处理操作 ->
    references/processing-recipes.md
  • 需要
    $
    、管道、流、配置的API细节 ->
    references/core-api.md
  • 组合多种模式(例如构建+处理) -> 阅读两个相关文件

Import Cheatsheet

导入速查表

// Core — always start here import { $, fs, path, glob, chalk } from 'zx/core';
// Additional utilities (import individually as needed)
import { spinner, retry, question, echo, sleep, within,
         stdin, tmpdir, tmpfile, which, ps, kill,
         quote, YAML, argv, fetch } from 'zx/core';
// 核心模块 —— 始终从此开始 import { $, fs, path, glob, chalk } from 'zx/core';
// 额外工具(按需单独导入)
import { spinner, retry, question, echo, sleep, within,
         stdin, tmpdir, tmpfile, which, ps, kill,
         quote, YAML, argv, fetch } from 'zx/core';

Conventions for Generated Scripts

生成脚本的约定

  1. Shebang line: Always include
    #!/usr/bin/env npx zx
    as the first line
  2. Error handling: Wrap top-level logic in a main function with try/catch, or use
    $.nothrow
    selectively
  3. Output: Use
    chalk
    for colored terminal output — green for success, red for errors, yellow for warnings, dim for secondary info
  4. Progress: Use
    spinner()
    for long-running operations in interactive contexts
  5. Arguments: Use
    argv
    (pre-parsed
    minimist
    ) for CLI argument handling
  6. Temp files: Use
    tmpdir()
    and
    tmpfile()
    — they auto-clean on exit
  7. Parallelism: Use
    Promise.all()
    with
    within()
    for parallel operations that need isolation
  1. Shebang行:始终将
    #!/usr/bin/env npx zx
    作为第一行
  2. 错误处理:将顶层逻辑包裹在主函数中并使用try/catch,或者选择性地使用
    $.nothrow
  3. 输出:使用
    chalk
    生成带颜色的终端输出——绿色表示成功,红色表示错误,黄色表示警告,灰色表示次要信息
  4. 进度展示:在交互式场景中,使用
    spinner()
    处理长时间运行的操作
  5. 参数处理:使用
    argv
    (预解析的
    minimist
    )处理CLI参数
  6. 临时文件:使用
    tmpdir()
    tmpfile()
    ——它们会在退出时自动清理
  7. 并行处理:将
    Promise.all()
    within()
    结合使用,实现需要隔离的并行操作