欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 nodejs 执行多个程序的 bash 脚本介绍 - zx 库

最编程 2024-06-16 11:15:52
...

官方网址:https://www.npmjs.com/package/zx

我们先看看怎么用

#!/usr/bin/env zx

await $`cat package.json | grep name`

let branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`

await Promise.all([
  $`sleep 1; echo 1`,
  $`sleep 2; echo 2`,
  $`sleep 3; echo 3`,
])

let name = 'foo bar'
await $`mkdir /tmp/${name}
登录后复制
登录后复制

各位看官觉得咋样,是不是就是在写linux命令而已,bash语法可以忽略很多,直接上js就行,而且它的优点还不止这些,有一些特点挺有意思的:

1、支持ts,自动编译.ts为.mjs文件,.mjs文件是node高版本自带的支持es6 module的文件结尾,也就是这个文件直接import模块就行,不用其它工具转义

2、自带支持管道操作pipe方法

3、自带fetch库,可以进行网络请求,自带chalk库,可以打印有颜色的字体,自带错误处理nothrow方法,如果bash命令出错,可以包裹在这个方法里忽略错误

完整中文文档(在下翻译水平一般,请见谅)

#!/usr/bin/env zx

await $`cat package.json | grep name`

let branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`

await Promise.all([
  $`sleep 1; echo 1`,
  $`sleep 2; echo 2`,
  $`sleep 3; echo 3`,
])

let name = 'foo bar'
await $`mkdir /tmp/${name}
登录后复制
登录后复制

Bash 很棒,但是在编写脚本时,人们通常会选择更方便的编程语言。 JavaScript 是一个完美的选择,但标准的 Node.js 库在使用之前需要额外的做一些事情。 zx 基于 child_process ,转义参数并提供合理的默认值。

安装

npm i -g zx
登录后复制

需要的环境

Node.js >= 14.8.0
登录后复制

将脚本写入扩展名为 .mjs 的文件中,以便能够在顶层使用await。

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

#!/usr/bin/env zx
现在您将能够像这样运行您的脚本:

chmod +x ./script.mjs
./script.mjs
登录后复制

或者通过 zx可执行文件:

zx ./script.mjs
登录后复制

所有函数($、cd、fetch 等)都可以直接使用,无需任何导入。

$`command`

使用 child_process 包中的 spawn 函数执行给定的字符串, 并返回 ProcessPromise.

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

例如,要并行上传文件:

如果执行的程序返回非零退出代码,ProcessOutput 将被抛出

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

ProcessPromise,以下是promise typescript的接口定义

class ProcessPromise<T> extends Promise<T> {
  readonly stdin: Writable
  readonly stdout: Readable
  readonly stderr: Readable
  readonly exitCode: Promise<number>
  pipe(dest): ProcessPromise<T>
}
登录后复制

pipe() 方法可用于重定向标准输出:

await $`cat file.txt`.pipe(process.stdout)
登录后复制

阅读更多的关于管道的信息:https://github.com/google/zx/blob/HEAD/examples/pipelines.md

ProcessOutput的typescript接口定义

class ProcessOutput {
  readonly stdout: string
  readonly stderr: string
  readonly exitCode: number
  toString(): string
}
登录后复制

函数:

cd()

更改当前工作目录

cd(&#39;/tmp&#39;)
await $`pwd` // outputs /tmp
登录后复制

fetch()

node-fetch 包。

let resp = await fetch(&#39;http://wttr.in&#39;)
if (resp.ok) {
  console.log(await resp.text())
}
登录后复制

question()

readline包

let bear = await question(&#39;What kind of bear is best? &#39;)
let token = await question(&#39;Choose env variable: &#39;, {
  choices: Object.keys(process.env)
})
登录后复制

在第二个参数中,可以指定选项卡自动完成的选项数组

以下是接口定义

function question(query?: string, options?: QuestionOptions): Promise<string>
type QuestionOptions = { choices: string[] }
登录后复制

sleep()

基于setTimeout 函数

await sleep(1000)
登录后复制

nothrow()

将 $ 的行为更改, 如果退出码不是0,不跑出异常.

ts接口定义

function nothrow<P>(p: P): P
登录后复制
await nothrow($`grep something from-file`)
// 在管道内:

await $`find ./examples -type f -print0`
  .pipe(nothrow($`xargs -0 grep something`))
  .pipe($`wc -l`)
登录后复制

以下的包,无需导入,直接使用

chalk

console.log(chalk.blue(&#39;Hello world!&#39;))
登录后复制

fs

类似于如下的使用方式

import {promises as fs} from &#39;fs&#39;
let content = await fs.readFile(&#39;./package.json&#39;)
登录后复制

os

await $`cd ${os.homedir()} && mkdir example`
登录后复制

配置:

$.shell

指定要用的bash.

$.shell = &#39;/usr/bin/bash&#39;
登录后复制

$.quote

指定用于在命令替换期间转义特殊字符的函数

默认用的是 shq 包.

注意:

__filename & __dirname这两个变量是在commonjs中的。我们用的是.mjs结尾的es6 模块。

在ESM模块中,Node.js 不提供__filename和 __dirname 全局变量。 由于此类全局变量在脚本中非常方便,因此 zx 提供了这些以在 .mjs 文件中使用(当使用 zx 可执行文件时)

require也是commonjs中的导入模块方法, 在 ESM 模块中,没有定义 require() 函数。zx提供了 require() 函数,因此它可以与 .mjs 文件中的导入一起使用(当使用 zx 可执行文件时)

传递环境变量

process.env.FOO = &#39;bar&#39;await $`echo $FOO`
登录后复制

传递数组

如果值数组作为参数传递给 $,数组的项目将被单独转义并通过空格连接 Example:

let files = [1,2,3]await $`tar cz ${files}`
登录后复制

可以通过显式导入来使用 $ 和其他函数

#!/usr/bin/env nodeimport {$} from &#39;zx&#39;await $`date`复制代码
登录后复制

zx 可以将 .ts 脚本编译为 .mjs 并执行它们

zx examples/typescript.ts
登录后复制

更多编程相关知识,请访问:编程视频!!

以上就是浅谈nodejs执行bash脚本的几种方案的详细内容,更多请关注php中文网其它相关文章!

推荐阅读