一经开源就爆了!谷歌这个脚本工具注定要火,


大家都知道Bash很好用,但是在编写脚本时,人们通常会选择一种更方便的编程语言,比如JavaScript,但是Node.js库在使用之前还需要许多额外的操作,整体来说还是不够方便,最近谷歌开源了一个能够帮助开发者快速编写脚本的工具——ZX,短短几天就登上了Github热榜。

ZX的安装十分简单:

  1. npm i -g zx 

接下来,你需要将你的脚本编写在带有.mjs扩展名的文件中,以便能够await在顶层使用。如果你喜欢.js扩展名,可以将脚本包装为void async function () {...}()。

将以下shebang添加到zx脚本的开头:

  1. #!/usr/bin/env zx 

现在,你将能够像这样运行脚本:

  1. chmod +x ./script.mjs  
  2. ./script.mjs 

或通过zx可执行文件:

  1. zx ./script.mjs 

常用命令举例

使用child_process包中提供的exec函数可以把字符串当做命令执行,并返回Promise<ProcessOutput>对象。

  1. let count = parseInt(await $`ls -1 | wc -l`)  
  2. console.log(`Files count: ${count}`) 

例如,要并行上传文件:

  1. let hosts = [...]  
  2. await Promise.all(hosts.map(host =>  
  3.   $`rsync -azP ./src ${host}:/var/www`    
  4. )) 

如果执行的程序返回一个非零的退出代码, 将会抛出ProcessOutput对象:

  1. try {  
  2.   await $`exit 1`  
  3. } catch (p) {  
  4.   console.log(`Exit code: ${p.exitCode}`)  
  5.   console.log(`Error: ${p.stderr}`)  

ProcessOutput

  1. class ProcessOutput {  
  2.   readonly exitCode: number  
  3.   readonly stdout: string  
  4.   readonly stderr: string  
  5.   toString(): string  

cd(),更改当前工作目录

  1. cd('/tmp')  
  2. await $`pwd` // outputs /tmp 

fetch(),对node-fetch包的包装:

  1. let resp = await fetch('http://wttr.in')  
  2. if (resp.ok) {  
  3.   console.log(await resp.text())  

question(),对readline包的包装:

  1. type QuestionOptions = { choices: string[] }  
  2. function question(query?: string, options?: QuestionOptions): Promise<string> 

用法:

  1. let username = await question('What is your username? ')  
  2. let token = await question('Choose env variable: ', { 
  3.   choices: Object.keys(process.env) 
  4. }) 

sleep(),setTimeout函数的包装。

  1. function sleep(ms: number): Promise<void> 

用法:

  1. await sleep(1000) 

chalk包,该包直接可用无需导入内部脚本:

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

执行远程脚本,如果zx可执行文件的参数以开头https://,则将下载并执行该文件。

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

最后,附上ZX在Github上的项目地址:https://github.com/google/zx 

相关内容