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

开源
最近谷歌开源了一个能够帮助开发者快速编写脚本的工具——ZX,短短几天就登上了Github热榜。

 大家都知道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  

 

责任编辑:庞桂玉 来源: 开源前线
相关推荐

2022-05-30 07:36:07

Python脚本函数

2022-08-02 20:21:00

SaaS驱动PLG

2021-10-29 06:56:15

Python脚本解释器

2021-04-12 13:36:59

开源技术 工具

2019-04-15 14:17:28

iTunes苹果macOS

2023-07-22 13:44:26

AI代码

2023-11-14 09:25:00

AI训练

2021-10-09 18:26:59

二叉树多叉树搜索

2021-05-13 10:20:44

谷歌工具技术

2019-12-24 09:49:02

微软英语浏览器

2023-08-01 14:07:05

模型AI

2021-01-27 11:36:34

代码开发工具

2023-03-02 11:44:08

AI技术

2015-12-30 10:36:59

2020-10-27 10:58:07

Linux内核操作系统

2023-05-11 11:46:58

AI翻唱

2023-04-03 09:56:22

模型系统

2023-05-16 14:07:52

AI自然语言

2011-10-11 10:39:30

2020-10-31 16:40:13

5G运营商通信
点赞
收藏

51CTO技术栈公众号