开源最前线(ID:OpenSourceTop) 猿妹整编
项目地址:https://github.com/google/zx
大家都知道Bash很好用,但是在编写脚本时,人们通常会选择一种更方便的编程语言,比如JavaScript,但是Node.js库在使用之前还需要许多额外的操作,整体来说还是不够方便,最近谷歌开源了一个能够帮助开发者快速编写脚本的工具——ZX,短短几天就登上了Github热榜。
npm i -g zx
接下来,你需要将你的脚本编写在带有.mjs扩展名的文件中,以便能够await在顶层使用。如果你喜欢.js扩展名,可以将脚本包装为void async function () {...}()。
#!/usr/bin/env zx
chmod +x ./script.mjs
./script.mjs
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}`)
}
class ProcessOutput {
readonly exitCode: number
readonly stdout: string
readonly stderr: string
toString(): string
}
cd('/tmp')
await $`pwd` // outputs /tmp
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