您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

浅谈nodejs执行bash脚本的几种方案

2024/8/11 6:43:47发布105次查看
nodejs如何执行bash脚本?本篇文章给大家介绍一下node执行bash脚本的几种方案。
前言最近在学习bash脚本语法,但是如果对bash语法不是熟手的话,感觉非常容易出错,比如说:显示未定义的变量shell中变量没有定义,仍然是可以使用的,但是它的结果可能不是你所预期的。举个例子:
#!/bin/bash# 这里是判断变量var是否等于字符串abc,但是var这个变量并没有声明if [ "$var" = "abc" ] then # 如果if判断里是true就在控制台打印 “ not abc” echo " not abc" else # 如果if判断里是false就在控制台打印 “ abc” echo " abc "fi
结果是打印了abc,但问题是,这个脚本应该报错啊,变量并没有赋值算是错误吧。
为了弥补这些错误,我们学会在脚本开头加入:set -u这句命令的意思是脚本在头部加上它,遇到不存在的变量就会报错,并停止执行。
再次运行就会提示:test.sh: 3: test.sh: num: parameter not set
再想象一下,你本来想删除:rm -rf $dir/*然后dir是空的时候,变成了什么?rm -rf是删除命令,$dir是空的话,相当于执行 rm -rf /*,这是删除所有文件和文件夹。。。然后,你的系统就没了,这就是传说中的删库跑路吗~~~~
如果是node或者浏览器环境,我们直接var === 'abc' 肯定是会报错的,也就是说很多javascript编程经验无法复用到bash来,如果能复用的话,该多好啊。
后来就开始探索,如果用node脚本代替bash该多好啊,经过一天折腾逐渐发现一个神器,google旗下的zx库,先别着急,我先不介绍这个库,我们先看看目前主流用node如何编写bash脚本,就知道为啥它是神器了。
node执行bash脚本: 勉强解决方案:child_process api例如 child_process的api里面exec命令
const { exec } = require("child_process");exec("ls -la", (error, stdout, stderr) => { if (error) { console.log(`error: ${error.message}`); return; } if (stderr) { console.log(`stderr: ${stderr}`); return; } console.log(`stdout: ${stdout}`);});
这里需要注意的是,首先exec是异步的,但是我们bash脚本命令很多都是同步的。
而且注意:error对象不同于stderr. error当child_process模块无法执行命令时,该对象不为空。例如,查找一个文件找不到该文件,则error对象不为空。但是,如果命令成功运行并将消息写入标准错误流,则该stderr对象不会为空。
当然我们可以使用同步的exec命令,execsync
// 引入 exec 命令 from child_process 模块const { execsync } = require("child_process");// 同步创建了一个hello的文件夹execsync("mkdir hello");
再简单介绍一下child_process的其它能够执行bash命令的api
spawn: 启动一个子进程来执行命令exec:启动一个子进程来执行命令,与spawn不同的是,它有一个回调函数能知道子进程的情况execfile:启动一子进程来执行可执行文件fork:与spawn类似,不同点是它需要指定子进程需要需执行的javascript文件exec跟ececfile不同的是,exec适合执行命令,eexecfile适合执行文件。
【推荐学习:《nodejs 教程》】
node执行bash脚本: 进阶方案 shelljsconst shell = require('shelljs'); # 删除文件命令shell.rm('-rf', 'out/release');// 拷贝文件命令shell.cp('-r', 'stuff/', 'out/release'); # 切换到lib目录,并且列出目录下到.js结尾到文件,并替换文件内容(sed -i 是替换文字命令)shell.cd('lib');shell.ls('*.js').foreach(function (file) { shell.sed('-i', 'build_version', 'v0.1.2', file); shell.sed('-i', /^.*remove_this_line.*$/, '', file); shell.sed('-i', /.*replace_line_with_macro.*\n/, shell.cat('macro.js'), file);});shell.cd('..'); # 除非另有说明,否则同步执行给定的命令。 在同步模式下,这将返回一个 shellstring#(与 shelljs v0.6.x 兼容,它返回一个形式为 { code:..., stdout:..., stderr:... } 的对象)。# 否则,这将返回子进程对象,并且回调接收参数(代码、标准输出、标准错误)。if (shell.exec('git commit -am "auto-commit"').code !== 0) { shell.echo('error: git commit failed'); shell.exit(1);}
从上面代码上看来,shelljs真的已经算是非常棒的nodejs写bash脚本的方案了,如果你们那边的node环境不能随便升级,我觉得shelljs确实够用了。
接着我们看看今天的主角zx,start已经17.4k了。
zx库官方网址:https://www.npmjs.com/package/zx
我们先看看怎么用
#!/usr/bin/env zxawait $`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 zxawait $`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('/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包
let bear = await question('what kind of bear is best? ')let token = await question('choose env variable: ', { 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`)
以下的包,无需导入,直接使用
chalkconsole.log(chalk.blue('hello world!'))
fs类似于如下的使用方式
import {promises as fs} from 'fs'let content = await fs.readfile('./package.json')
osawait $`cd ${os.homedir()} && mkdir example`
配置:
$.shell指定要用的bash.
$.shell = '/usr/bin/bash'
$.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 = 'bar'await $`echo $foo`
传递数组如果值数组作为参数传递给 $,数组的项目将被单独转义并通过空格连接example:
let files = [1,2,3]await $`tar cz ${files}`
可以通过显式导入来使用 $ 和其他函数
#!/usr/bin/env nodeimport {$} from 'zx'await $`date`复制代码
zx 可以将 .ts 脚本编译为 .mjs 并执行它们
zx examples/typescript.ts
更多编程相关知识,请访问:编程视频!!
以上就是浅谈nodejs执行bash脚本的几种方案的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product