专栏名称: 开源前线
推荐热门开源软件,播报最新开源项目和开源资讯!
目录
相关文章推荐
三联生活周刊  ·  分享欲不对等,令我的八年友谊陷入危机 ·  7 小时前  
单读  ·  许知远:异乡人的 Love Letters ·  20 小时前  
新周刊  ·  DeepSeek强推的西北“小江南”,春天不 ... ·  3 天前  
51好读  ›  专栏  ›  开源前线

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

开源前线  · 公众号  ·  · 2021-05-18 10:24

正文


开源最前线(ID:OpenSourceTop) 猿妹整编

项目地址:https://github.com/google/zx


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



ZX的安装十分简单:


npm i -g zx


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

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


#!/usr/bin/env zx


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


chmod +x ./script.mjs
./script.mjs


或通过zx可执行文件:


zx ./script.mjs



常用命令举例

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


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


例如,要并行上传文件:


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


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


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


ProcessOutput


class ProcessOutput {
  readonly exitCode: number
  readonly stdout: string
  readonly stderr: string
  toString(): string
}


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


cd('/tmp')
await $`pwd` // outputs /tmp


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


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


question(),对readline包的包装:


type QuestionOptions = { choices: string[] }

function question(query?: string, options?: QuestionOptions): Promise<string>


用法:


let username = await question('What is your username? ')
let






请到「今天看啥」查看全文