自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Nodejs 寫 Bash 腳本終極方案!

開發(fā) 前端
最近在學(xué)習(xí)bash腳本語法,但是如果對bash語法不是熟手的話,感覺非常容易出錯,比如說:顯示未定義的變量shell中變量沒有定義,仍然是可以使用的,但是它的結(jié)果可能不是你所預(yù)期的。

 [[420368]]

前言

最近在學(xué)習(xí)bash腳本語法,但是如果對bash語法不是熟手的話,感覺非常容易出錯,比如說:顯示未定義的變量shell中變量沒有定義,仍然是可以使用的,但是它的結(jié)果可能不是你所預(yù)期的。舉個例子: 

  1. #!/bin/bash  
  2. # 這里是判斷變量var是否等于字符串a(chǎn)bc,但是var這個變量并沒有聲明  
  3. if [ "$var" = "abc" ]   
  4. then  
  5.    # 如果if判斷里是true就在控制臺打印 “ not abc”  
  6.    echo  " not abc"   
  7. else  
  8.    # 如果if判斷里是false就在控制臺打印 “ abc”  
  9.    echo " abc "  
  10. fi  
  11. 復(fù)制代碼 

結(jié)果是打印了abc,但問題是,這個腳本應(yīng)該報錯啊,變量并沒有賦值算是錯誤吧。

為了彌補這些錯誤,我們學(xué)會在腳本開頭加入:set \-u 這句命令的意思是腳本在頭部加上它,遇到不存在的變量就會報錯,并停止執(zhí)行。

再次運行就會提示:test.sh: 3: test.sh: num: parameter not set

再想象一下,你本來想刪除:rm \-rf $dir/*然后dir是空的時候,變成了什么?rm \-rf是刪除命令,$dir是空的話,相當于執(zhí)行 rm \-rf /*,這是刪除所有文件和文件夾。。。然后,你的系統(tǒng)就沒了,這就是傳說中的刪庫跑路嗎~~~~

如果是node或者瀏覽器環(huán)境,我們直接var === 'abc' 肯定是會報錯的,也就是說很多javascript編程經(jīng)驗無法復(fù)用到bash來,如果能復(fù)用的話,該多好啊。

后來就開始探索,如果用node腳本代替bash該多好啊,經(jīng)過一天折騰逐漸發(fā)現(xiàn)一個神器,Google旗下的zx庫,先別著急,我先不介紹這個庫,我們先看看目前主流用node如何編寫bash腳本,就知道為啥它是神器了。

node執(zhí)行bash腳本: 勉強解決方案:child_process API

例如 child_process的API里面exec命令 

  1. const { exec } = require("child_process");  
  2. exec("ls -la", (error, stdout, stderr) => {  
  3.     if (error) {  
  4.         console.log(`error: ${error.message}`);  
  5.         return;  
  6.     }  
  7.     if (stderr) {  
  8.         console.log(`stderr: ${stderr}`);  
  9.         return;  
  10.     }  
  11.     console.log(`stdout: ${stdout}`);  
  12. });  
  13. 復(fù)制代碼 

這里需要注意的是,首先exec是異步的,但是我們bash腳本命令很多都是同步的。

而且注意:error對象不同于stderr. error當child_process模塊無法執(zhí)行命令時,該對象不為空。例如,查找一個文件找不到該文件,則error對象不為空。但是,如果命令成功運行并將消息寫入標準錯誤流,則該stderr對象不會為空。

當然我們可以使用同步的exec命令,execSync 

  1. // 引入 exec 命令 from child_process 模塊  
  2. const { execSync } = require("child_process");  
  3. // 同步創(chuàng)建了一個hello的文件夾  
  4. execSync("mkdir hello");  
  5. 復(fù)制代碼 

再簡單介紹一下child_process的其它能夠執(zhí)行bash命令的api

  •  spawn:啟動一個子進程來執(zhí)行命令
  •  exec:啟動一個子進程來執(zhí)行命令,與spawn不同的是,它有一個回調(diào)函數(shù)能知道子進程的情況
  •  execFile:啟動一子進程來執(zhí)行可執(zhí)行文件
  •  fork:與spawn類似,不同點是它需要指定子進程需要需執(zhí)行的javascript文件

exec跟ececFile不同的是,exec適合執(zhí)行命令,eexecFile適合執(zhí)行文件。

node執(zhí)行bash腳本: 進階方案 shelljs 

  1. const shell = require('shelljs');  
  2.  # 刪除文件命令  
  3. shell.rm('-rf', 'out/Release');  
  4. // 拷貝文件命令  
  5. shell.cp('-R', 'stuff/', 'out/Release');   
  6. # 切換到lib目錄,并且列出目錄下到.js結(jié)尾到文件,并替換文件內(nèi)容(sed -i 是替換文字命令)  
  7. shell.cd('lib');  
  8. shell.ls('*.js').forEach(function (file) {  
  9.   shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);  
  10.   shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); 
  11.   shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);  
  12. });  
  13. shell.cd('..');  
  14. # 除非另有說明,否則同步執(zhí)行給定的命令。 在同步模式下,這將返回一個 ShellString 
  15. #(與 ShellJS v0.6.x 兼容,它返回一個形式為 { code:..., stdout:..., stderr:... } 的對象)。  
  16. # 否則,這將返回子進程對象,并且回調(diào)接收參數(shù)(代碼、標準輸出、標準錯誤)。  
  17. if (shell.exec('git commit -am "Auto-commit"').code !== 0) {  
  18.   shell.echo('Error: Git commit failed');  
  19.   shell.exit(1);  
  20.  
  21. 復(fù)制代碼 

從上面代碼上看來,shelljs真的已經(jīng)算是非常棒的nodejs寫bash腳本的方案了,如果你們那邊的node環(huán)境不能隨便升級,我覺得shelljs確實夠用了。

接著我們看看今天的主角zx,start已經(jīng)17.4k了。

zx庫

官方網(wǎng)址:www.npmjs.com/package/zx[1]

我們先看看怎么用 

  1. #!/usr/bin/env zx  
  2. await $`cat package.json | grep name`  
  3. let branch = await $`git branch --show-current`  
  4. await $`dep deploy --branch=${branch}`  
  5. await Promise.all([  
  6.   $`sleep 1; echo 1`,  
  7.   $`sleep 2; echo 2`,  
  8.   $`sleep 3; echo 3`,  
  9. ])  
  10. let name = 'foo bar'  
  11. await $`mkdir /tmp/${name}  
  12. 復(fù)制代碼 

各位看官覺得咋樣,是不是就是在寫linux命令而已,bash語法可以忽略很多,直接上js就行,而且它的優(yōu)點還不止這些,有一些特點挺有意思的:

1、支持ts,自動編譯.ts為.mjs文件,.mjs文件是node高版本自帶的支持es6 module的文件結(jié)尾,也就是這個文件直接import模塊就行,不用其它工具轉(zhuǎn)義

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

3、自帶fetch庫,可以進行網(wǎng)絡(luò)請求,自帶chalk庫,可以打印有顏色的字體,自帶錯誤處理nothrow方法,如果bash命令出錯,可以包裹在這個方法里忽略錯誤

完整中文文檔(在下翻譯水平一般,請見諒) 

  1. #!/usr/bin/env zx  
  2. await $`cat package.json | grep name`  
  3. let branch = await $`git branch --show-current`  
  4. await $`dep deploy --branch=${branch}`  
  5. await Promise.all([  
  6.   $`sleep 1; echo 1`,  
  7.   $`sleep 2; echo 2`,  
  8.   $`sleep 3; echo 3`,  
  9. ])  
  10. let name = 'foo bar'  
  11. await $`mkdir /tmp/${name}  
  12. 復(fù)制代碼 

Bash 很棒,但是在編寫腳本時,人們通常會選擇更方便的編程語言。JavaScript 是一個完美的選擇,但標準的 Node.js 庫在使用之前需要額外的做一些事情。zx 基于 child_process ,轉(zhuǎn)義參數(shù)并提供合理的默認值。

安裝 

  1. npm i -g zx  
  2. 復(fù)制代碼 

需要的環(huán)境 

  1. Node.js >= 14.8.0  
  2. 復(fù)制代碼 

將腳本寫入擴展名為 .mjs 的文件中,以便能夠在頂層使用await。

將以下 shebang添加到 zx 腳本的開頭: 

  1. #!/usr/bin/env zx  
  2. 現(xiàn)在您將能夠像這樣運行您的腳本:  
  3. chmod +x ./script.mjs  
  4. ./script.mjs  
  5. 復(fù)制代碼 

或者通過 zx可執(zhí)行文件: 

  1. zx ./script.mjs  
  2. 復(fù)制代碼 

所有函數(shù)($、cd、fetch 等)都可以直接使用,無需任何導(dǎo)入。

$`command`

使用 child_process 包中的 spawn 函數(shù)執(zhí)行給定的字符串, 并返回 ProcessPromise. 

  1. let count = parseInt(await $`ls -1 | wc -l`)  
  2. console.log(`Files count: ${count}`)  
  3. 復(fù)制代碼 

例如,要并行上傳文件:

如果執(zhí)行的程序返回非零退出代碼,ProcessOutput 將被拋出 

  1. try {  
  2.   await $`exit 1`  
  3. } catch (p) {  
  4.   console.log(`Exit code: ${p.exitCode}`)  
  5.   console.log(`Error: ${p.stderr}`)  
  6.  
  7. 復(fù)制代碼 

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

  1. class ProcessPromise<T> extends Promise<T> {  
  2.   readonly stdin: Writable  
  3.   readonly stdout: Readable  
  4.   readonly stderr: Readable  
  5.   readonly exitCode: Promise<number>  
  6.   pipe(dest): ProcessPromise<T>  
  7.  
  8. 復(fù)制代碼 

pipe() 方法可用于重定向標準輸出: 

  1. await $`cat file.txt`.pipe(process.stdout)  
  2. 復(fù)制代碼 

閱讀更多的關(guān)于管道的信息 github.com/google/zx/b…[2]

ProcessOutput的typescript接口定義 

  1. class ProcessOutput {  
  2.   readonly stdout: string  
  3.   readonly stderr: string  
  4.   readonly exitCode: number  
  5.   toString(): string  
  6. 復(fù)制代碼 

函數(shù):

cd()

更改當前工作目錄 

  1. cd('/tmp')  
  2. await $`pwd` // outputs /tmp  
  3. 復(fù)制代碼 

fetch()

node-fetch 包。 

  1. let resp = await fetch('http://wttr.in')  
  2. if (resp.ok) {  
  3.   console.log(await resp.text())  
  4.  
  5. 復(fù)制代碼 

question()

readline包 

  1. let bear = await question('What kind of bear is best? ')  
  2. let token = await question('Choose env variable: ', {  
  3.   choices: Object.keys(process.env)  
  4. }) 
  5. 復(fù)制代碼 

在第二個參數(shù)中,可以指定選項卡自動完成的選項數(shù)組

以下是接口定義 

  1. function question(query?: string, options?: QuestionOptions): Promise<string>  
  2. type QuestionOptions = { choices: string[] }  
  3. 復(fù)制代碼 

sleep()

基于setTimeout 函數(shù) 

  1. await sleep(1000)  
  2. 復(fù)制代碼 

nothrow()

將 $ 的行為更改, 如果退出碼不是0,不跑出異常.

ts接口定義 

  1. function nothrow<P>(p: P): P  
  2. 復(fù)制代碼  
  1. await nothrow($`grep something from-file`)  
  2. // 在管道內(nèi): 
  3. await $`find ./examples -type f -print0`  
  4.   .pipe(nothrow($`xargs -0 grep something`))  
  5.   .pipe($`wc -l`)  
  6. 復(fù)制代碼 

以下的包,無需導(dǎo)入,直接使用

chalk 

  1. console.log(chalk.blue('Hello world!'))  
  2. 復(fù)制代碼 

fs

類似于如下的使用方式 

  1. import {promises as fs} from 'fs'  
  2. let content = await fs.readFile('./package.json')  
  3. 復(fù)制代碼 

os 

  1. await $`cd ${os.homedir()} && mkdir example`  
  2. 復(fù)制代碼 

配置:

$.shell

指定要用的bash. 

  1. $.shell = '/usr/bin/bash'  
  2. 復(fù)制代碼 

$.quote

指定用于在命令替換期間轉(zhuǎn)義特殊字符的函數(shù)

默認用的是 shq 包.

注意:

__filename & __dirname這兩個變量是在commonjs中的。我們用的是.mjs結(jié)尾的es6 模塊。

在ESM模塊中,Node.js 不提供__filename和 __dirname 全局變量。由于此類全局變量在腳本中非常方便,因此 zx 提供了這些以在 .mjs 文件中使用(當使用 zx 可執(zhí)行文件時)

require也是commonjs中的導(dǎo)入模塊方法, 在 ESM 模塊中,沒有定義 require() 函數(shù)。zx提供了 require() 函數(shù),因此它可以與 .mjs 文件中的導(dǎo)入一起使用(當使用 zx 可執(zhí)行文件時)

傳遞環(huán)境變量 

  1. process.env.FOO = 'bar'  
  2. await $`echo $FOO`  
  3. 復(fù)制代碼 

傳遞數(shù)組

如果值數(shù)組作為參數(shù)傳遞給 $,數(shù)組的項目將被單獨轉(zhuǎn)義并通過空格連接 Example: 

  1. let files = [1,2,3]  
  2. await $`tar cz ${files}`  
  3. 復(fù)制代碼 

可以通過顯式導(dǎo)入來使用 $ 和其他函數(shù) 

  1. #!/usr/bin/env node  
  2. import {$} from 'zx'  
  3. await $`date`  
  4. 復(fù)制代碼 

zx 可以將 .ts 腳本編譯為 .mjs 并執(zhí)行它們 

  1. zx examples/typescript.ts  
  2. 復(fù)制代碼 

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2021-09-14 13:00:17

nodejsbash前端

2020-09-11 16:00:40

Bash單元測試

2022-03-10 10:12:04

自動化腳本Bash

2023-08-23 12:12:45

BashLinux

2025-03-05 11:10:55

2022-05-30 10:31:34

Bash腳本Linux

2014-08-05 11:17:28

Bash腳本測試

2021-05-19 17:25:12

Pythonexe命令

2022-12-01 08:10:49

Bash腳本參數(shù)

2023-08-29 08:57:03

事務(wù)腳本架構(gòu)模式業(yè)務(wù)場景

2020-10-13 19:04:58

Bash信號捕獲Shell腳本

2022-01-20 16:43:38

Bash 腳本ShellLinux

2022-02-28 11:02:53

函數(shù)Bash Shell語句

2017-04-13 10:51:17

Bash建議

2021-02-01 11:01:18

Bash腳本Linux

2021-03-11 21:30:43

BATSBash軟件開發(fā)

2021-12-30 10:26:37

Bash Shell腳本文件命令

2022-11-30 07:47:00

Bash腳本

2022-11-25 07:53:26

bash腳本字符串

2010-06-23 15:55:36

Linux Bash
點贊
收藏

51CTO技術(shù)棧公眾號