node執(zhí)行cmd或shell命令使用介紹
引言
在實(shí)現(xiàn)前端工程化的過程中,經(jīng)常需要在一個(gè)js腳本中去執(zhí)行其他node
/npm
或者其他shell
命令。本篇就介紹兩種node
調(diào)用shell
的方法。
一、node原生模塊:child_process
node原生API介紹:child_process.exec()
: 衍生 shell 并在該 shell 中運(yùn)行命令,完成后將 stdout 和 stderr 傳給回調(diào)函數(shù)。
child_process.execFile()
: 與 child_process.exec() 類似,不同之處在于,默認(rèn)情況下,它直接衍生命令,而不先衍生 shell。
child_process.fork()
: 衍生新的 Node.js 進(jìn)程并使用建立的 IPC 通信通道(其允許在父子進(jìn)程之間發(fā)送消息)調(diào)用指定的模塊。
child_process.execSync()
: child_process.exec() 的同步版本,其將阻塞 Node.js 事件循環(huán)。
child_process.execFileSync()
: child_process.execFile() 的同步版本,其將阻塞 Node.js 事件循環(huán)。
使用
const process = require("child_process"); // 執(zhí)行 npm run build 命令 ;(function() { process.exec('npm run build', (error, stdout, stderr) => { if (!error) { // 成功 } else { // 失敗 } }); })();
二、npm包:shelljs
- 安裝
npm i -D shelljs
- 使用
const shell = require('shelljs'); // 同步 // 執(zhí)行 git status 命令 const { code } = shell.exec('git status'); /* * 返回一個(gè)對(duì)象 * 可以根據(jù) code 值來判斷當(dāng)前命令是否執(zhí)行成功 * code === 0 代表成功 * */ // 異步回調(diào) // 執(zhí)行 git add . 命令 shell.exec('git add .', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); if (code===0) { console.log('成功') // do something } });
參考文檔:
http://nodejs.cn/api/child_process.html
https://www.npmjs.com/package/shelljs
以上就是node執(zhí)行cmd或shell命令使用介紹的詳細(xì)內(nèi)容,更多關(guān)于node執(zhí)行cmd shell命令的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Node.js 多線程實(shí)戰(zhàn)小結(jié)
在?Node.js?的世界中,多線程技術(shù)一直是一個(gè)受到廣泛關(guān)注的領(lǐng)域,本文主要介紹了Node.js 多線程實(shí)戰(zhàn)小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01Node.JS在命令行中檢查Chrome瀏覽器是否安裝并打開指定網(wǎng)址
這篇文章主要介紹了Node.JS在命令行中檢查Chrome瀏覽器是否安裝,并打開指定網(wǎng)址,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05Node.js?中的?module.exports?與?exports區(qū)別介紹
這篇文章主要介紹了Node.js中的module.exports與exports區(qū)別介紹,每個(gè)模塊中都有module對(duì)象,存放了當(dāng)前模塊相關(guān)的信息,更多相關(guān)內(nèi)容需要的朋友可以參考一下2022-09-09如何使用nvm實(shí)現(xiàn)nodejs版本管理(版本刪除,版本切換及版本添加)
這篇文章主要給大家介紹了關(guān)于如何使用nvm實(shí)現(xiàn)nodejs版本管理(版本刪除,版本切換及版本添加)的相關(guān)資料,nvm是一個(gè)node版本管理工具,通過它可以安裝多種node版本并且可以快速、簡(jiǎn)單的切換node版本,需要的朋友可以參考下2023-10-10使用nodejs?spider爬取圖片及數(shù)據(jù)實(shí)現(xiàn)
這篇文章主要為大家介紹了使用nodejs?spider爬取圖片及數(shù)據(jù)實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Node.js使用對(duì)話框ngDialog的示例代碼
本篇文章主要介紹了Node.js使用對(duì)話框ngDialog的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05基于Alpine Linux構(gòu)建前端node-web鏡像步驟詳解
這篇文章主要為大家介紹了基于Alpine Linux構(gòu)建前端node-web鏡像步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11