google-zx-scripting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGoogle ZX Scripting
Google ZX 脚本编写
Use this skill when writing scripts with Google's library — the tool that makes shell scripting with JavaScript/TypeScript productive and safe. Read only the reference file(s) needed for the task.
zx当你使用Google的库编写脚本时可以使用本技能——zx是一款让JavaScript/TypeScript编写Shell脚本高效且安全的工具。仅阅读完成任务所需的参考文件即可。
zxQuick Start
快速开始
All zx scripts use the lite entry point for portability. Scripts are standalone files — no project setup required.
.mjs#!/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.mjsCritical Rules
重要规则
- Always use — import from
zx/core(the lite bundle), never barezx/core. This avoids the heavy CLI wrapper and keeps scripts lean and embeddable.zx - Template literals auto-escape — interpolated values in are automatically shell-quoted. Never manually quote interpolated variables:
$`...`is safe,$`echo ${userInput}`double-quotes and may break.$`echo "${userInput}"` - Arrays expand correctly — expands each element as a separate quoted argument. Use this for flags, file lists, etc.
$`cmd ${arrayOfArgs}` - Non-zero exits throw — by default, a failed command throws as an error. Use
ProcessOutputoption ornothrowto suppress when you expect failures (e.g.,.nothrow()returning no matches).grep - Use for isolation —
within()creates an async scope with its ownwithin(),$.cwd, and other settings. Essential for parallel tasks that need different working directories.$.env - Pipe with — use
.pipe()instead of shell pipes. This keeps each process managed by zx.$`cmd1`.pipe($`cmd2`) - Prefer zx builtins over shell commands — use instead of
glob(),findinstead offs/cat/cp,mvinstead offetch(). These are cross-platform and return proper JS types.curl - is global —
cd()changescd()for ALL subsequent commands. Use$.cwdorwithin()for scoped directory changes.$({cwd: '/path'}) - Scripts must be — use
.mjsextension for top-level.mjssupport without bundler config.await
- 始终使用—— 从
zx/core(轻量包)导入,绝不要直接导入zx/core。这样可以避免庞大的CLI包装器,保持脚本精简且可嵌入。zx - 模板字面量自动转义 —— 中的插值变量会自动进行Shell转义。绝不要手动为插值变量添加引号:
$`...`是安全的,而$`echo ${userInput}`会添加双引号,可能导致脚本出错。$`echo "${userInput}"` - 数组正确展开 —— 会将数组中的每个元素展开为单独的带引号参数。可用于标志、文件列表等场景。
$`cmd ${arrayOfArgs}` - 非零退出码会抛出异常 —— 默认情况下,执行失败的命令会抛出错误。当你预期会出现失败(例如
ProcessOutput未匹配到内容)时,使用grep选项或nothrow来抑制异常。.nothrow() - 使用实现隔离 ——
within()会创建一个异步作用域,拥有独立的within()、$.cwd和其他设置。对于需要不同工作目录的并行任务来说至关重要。$.env - 使用实现管道 —— 使用
.pipe()替代Shell管道。这样可以让每个进程都由zx管理。$`cmd1`.pipe($`cmd2`) - 优先使用zx内置工具而非Shell命令 —— 使用替代
glob(),使用find替代fs/cat/cp,使用mv替代fetch()。这些工具是跨平台的,并且会返回标准的JS类型。curl - 是全局的 ——
cd()会修改所有后续命令的cd()。如果需要作用域内的目录切换,请使用$.cwd或within()。$({cwd: '/path'}) - 脚本必须为格式 —— 使用
.mjs扩展名以支持顶级.mjs,无需打包器配置。await
Reference Map
参考映射
| Need | File |
|---|---|
| |
| Ad-hoc scripts, CLI tools, build scripts, deployment, project scaffolding | |
| File processing, data pipelines, batch ops, AI scripts, log analysis | |
| 需求 | 文件 |
|---|---|
| |
| 临时脚本、CLI工具、构建脚本、部署、项目脚手架 | |
| 文件处理、数据管道、批处理操作、AI脚本、日志分析 | |
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
生成脚本的约定
- Shebang line: Always include as the first line
#!/usr/bin/env npx zx - Error handling: Wrap top-level logic in a main function with try/catch, or use selectively
$.nothrow - Output: Use for colored terminal output — green for success, red for errors, yellow for warnings, dim for secondary info
chalk - Progress: Use for long-running operations in interactive contexts
spinner() - Arguments: Use (pre-parsed
argv) for CLI argument handlingminimist - Temp files: Use and
tmpdir()— they auto-clean on exittmpfile() - Parallelism: Use with
Promise.all()for parallel operations that need isolationwithin()
- Shebang行:始终将作为第一行
#!/usr/bin/env npx zx - 错误处理:将顶层逻辑包裹在主函数中并使用try/catch,或者选择性地使用
$.nothrow - 输出:使用生成带颜色的终端输出——绿色表示成功,红色表示错误,黄色表示警告,灰色表示次要信息
chalk - 进度展示:在交互式场景中,使用处理长时间运行的操作
spinner() - 参数处理:使用(预解析的
argv)处理CLI参数minimist - 临时文件:使用和
tmpdir()——它们会在退出时自动清理tmpfile() - 并行处理:将与
Promise.all()结合使用,实现需要隔离的并行操作within()