1. ZX 介绍 zx 是 google 的一个脚本工具, 可以帮助开发者轻松的编写脚本, 主要有以下优势:
2. 代码演练 example.mjs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 #!/usr/ bin/env zx import { $, echo, os, chalk } from "zx" ;try { const projectName = await $`jq -r '.name' < package.json` ; echo`1. projectName: ${projectName} ` ; } catch (e) { const { stderr, exitCode } = e; console .error ({ stderr, exitCode }); } const date = await $`date` ;console .log (`2. Current date is ${date.stdout.trim()} .` );echo`3. Current date is ${date} .` ; const echoResult = await $`echo 4. Current date is ${date} .` ; echo`${echoResult} ` ; console .log ("console.log" , chalk.blue ("蓝色" ));console .log (`console.log ${chalk.blue("蓝色" )} template` );echo ("echo" , chalk.blue ("蓝色" ));echo (`echo ${chalk.blue("蓝色" )} template ` );const batchResult = await Promise .all ([ $`sleep 1; echo 1` , $`sleep 2; echo 2` , $`sleep 3; echo 3` , ]); for (const result of batchResult) { echo`batch result: ${result} ` ; } await $`echo "Hello, stdout!"` .pipe ( fs.createWriteStream (`${__dirname} /output.txt` ) ); echo`home目录: ${os.homedir()} ` ; echo`日志目录: ${path.resolve(path.join(os.homedir(), "tmp" , "output.log" ))} ` ; echo`当前目录: ${__dirname} ` ;
[!note] 第三行的引用实则未必, 但是在写脚本时候可以提供很多类型感知防止写错; 另外如果脚本依赖第三方包也是需要在前面引用的.
结果输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 1. projectName: albedo-services 2. Current date is Wed Apr 10 15:03:36 CST 2024. 3. Current date is Wed Apr 10 15:03:36 CST 2024. 4. Current date is Wed Apr 10 15:03:36 CST 2024. console.log 蓝色 console.log 蓝色 template echo 蓝色 echo 蓝色 template batch result: 1 batch result: 2 batch result: 3 home目录: /Users/wangjian 日志目录: /Users/wangjian/tmp/output.log 当前目录: /Users/wangjian/github/vd/albedo-services/tmp/zxshell
3. 执行方式
可执行文件执行
1 2 3 4 chmod +x example.mjs./example.mjs
[!note]
确保 shebang 已配置, zx 的 shengbang 是: #!/usr/bin/env zx
zx 执行
1 2 3 4 5 6 npm install -g zx brew install zx zx ./example.mjs
4. 学习更多