nodejs如何执行bash脚本?本篇文章给大家介绍一下node执行bash脚本的几种方案。
|
nodejs如何执行bash脚本?本篇文章给大家介绍一下node执行bash脚本的几种方案。
前言最近在学习 #!/bin/bash # 这里是判断变量var是否等于字符串abc,但是var这个变量并没有声明 if [ "$var" = "abc" ] then # 如果if判断里是true就在控制台打印 “ not abc” echo " not abc" else # 如果if判断里是false就在控制台打印 “ abc” echo " abc " fi 结果是打印了abc,但问题是,这个脚本应该报错啊,变量并没有赋值算是错误吧。 为了弥补这些错误,我们学会在脚本开头加入: 再次运行就会提示:test.sh: 3: test.sh: num: parameter not set 再想象一下,你本来想删除: 如果是 后来就开始探索,如果用 node执行bash脚本: 勉强解决方案:child_process API例如 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 命令 from child_process 模块
const { execSync } = require("child_process");
// 同步创建了一个hello的文件夹
execSync("mkdir hello");再简单介绍一下child_process的其它能够执行bash命令的api
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 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 将脚本写入扩展名为 将以下 #!/usr/bin/env zx 现在您将能够像这样运行您的脚本: chmod +x ./script.mjs ./script.mjs 或者通过 zx ./script.mjs 所有函数 $`command`使用 let count = parseInt(await $`ls -1 | wc -l`)
console.log(`Files count: ${count}`)例如,要并行上传文件: 如果执行的程序返回非零退出代码, 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>
}
await $`cat file.txt`.pipe(process.stdout) 阅读更多的关于管道的信息:https://github.com/google/zx/blob/HEAD/examples/pipelines.md
class ProcessOutput {
readonly stdout: string
readonly stderr: string
readonly exitCode: number
toString(): string
}函数: cd()更改当前工作目录 cd('/tmp')
await $`pwd` // outputs /tmpfetch()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 包. 注意:
在
传递环境变量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脚本的几种方案的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |
