当前位置:首页 >休闲 >一经开源就爆了!谷歌这个脚本工具注定要火 短短几天就登上了Github热榜

一经开源就爆了!谷歌这个脚本工具注定要火 短短几天就登上了Github热榜

2024-06-28 10:00:17 [百科] 来源:避面尹邢网

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

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

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

一经开源就爆了!谷歌这个脚本工具注定要火 短短几天就登上了Github热榜

ZX的源爆安装十分简单: 

一经开源就爆了!谷歌这个脚本工具注定要火 短短几天就登上了Github热榜

  1. npm i -g zx 

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

一经开源就爆了!谷歌这个脚本工具注定要火 短短几天就登上了Github热榜

将以下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  

 

责任编辑:庞桂玉 来源: 开源前线 开源脚本工具

(责任编辑:热点)

    推荐文章
    热点阅读