一經(jīng)開源就爆了!谷歌這個(gè)腳本工具注定要火
大家都知道Bash很好用,但是在編寫腳本時(shí),人們通常會(huì)選擇一種更方便的編程語(yǔ)言,比如JavaScript,但是Node.js庫(kù)在使用之前還需要許多額外的操作,整體來說還是不夠方便,最近谷歌開源了一個(gè)能夠幫助開發(fā)者快速編寫腳本的工具——ZX,短短幾天就登上了Github熱榜。
ZX的安裝十分簡(jiǎn)單:
- npm i -g zx
接下來,你需要將你的腳本編寫在帶有.mjs擴(kuò)展名的文件中,以便能夠await在頂層使用。如果你喜歡.js擴(kuò)展名,可以將腳本包裝為void async function () {...}()。
將以下shebang添加到zx腳本的開頭:
- #!/usr/bin/env zx
現(xiàn)在,你將能夠像這樣運(yùn)行腳本:
- chmod +x ./script.mjs
- ./script.mjs
或通過zx可執(zhí)行文件:
- zx ./script.mjs
常用命令舉例
使用child_process包中提供的exec函數(shù)可以把字符串當(dāng)做命令執(zhí)行,并返回Promise<ProcessOutput>對(duì)象。
- 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`
- ))
如果執(zhí)行的程序返回一個(gè)非零的退出代碼, 將會(huì)拋出ProcessOutput對(duì)象:
- 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(),更改當(dāng)前工作目錄
- cd('/tmp')
- await $`pwd` // outputs /tmp
fetch(),對(duì)node-fetch包的包裝:
- let resp = await fetch('http://wttr.in')
- if (resp.ok) {
- console.log(await resp.text())
- }
question(),對(duì)readline包的包裝:
- type QuestionOptions = { choices: string[] }
- function question(query?: string, options?: QuestionOptions): Promise<string>
用法:
- let username = await question('What is your username? ')
- let token = await question('Choose env variable: ', {
- choices: Object.keys(process.env)
- })
sleep(),setTimeout函數(shù)的包裝。
- function sleep(ms: number): Promise<void>
用法:
- await sleep(1000)
chalk包,該包直接可用無需導(dǎo)入內(nèi)部腳本:
- console.log(chalk.blue('Hello world!'))
執(zhí)行遠(yuǎn)程腳本,如果zx可執(zhí)行文件的參數(shù)以開頭https://,則將下載并執(zhí)行該文件。
- console.log(chalk.blue('Hello world!'))
最后,附上ZX在Github上的項(xiàng)目地址:https://github.com/google/zx