child_process模塊是nodejs的一個子進程模塊,能夠用來建立一個子進程,並執行一些任務。執行一些什麼任務呢?shell命令知道吧,有了child_process模塊,就能夠直接在js裏面調用shell命令去完成一些很是酷炫的操做了!!
舉個栗子,GitHub、碼雲等git代碼託管網站,都會有個webHook功能,當push了新的代碼後,服務器能夠開闢一個接口去接受這個webHook的請求,並進行git pull
、npm run build
等命令,從而達到自動化部署的目的!html
前端直接簡單用的vue-cli
腳手架新建了個項目,後端是用的express前端
前端代碼就不曬了,都是腳手架生成的,後端代碼主要就是一個server.js
和一個執行shell的方法。vue
backend/server.js
注意先要安裝幾個依賴:express
和body-parser
express
是主角,不用多說,body-parser
是用來解析post請求的參數的。
const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const www = process.env.WWW || './fontend/dist'; var bodyParser = require('body-parser')//格式化body數據 app.use(bodyParser.urlencoded({extended: false}));//body parser插件配置 app.use(bodyParser.json());//body parser插件配置 const gitPush = require('./service/git-push')//引入寫的服務 app.post('/api/git_hook',async (req, res) => {//監聽這個接口 if(req.body.password !== '666'){// 這裏校驗post請求的密碼 res.send('密碼錯誤') return } const code = await gitPush() res.send('hello world' + code) }) app.use(express.static(www)); console.log(`serving ${www}`); app.get('*', (req, res) => { res.sendFile(`index.html`, { root: www }); }); app.listen(port, () => console.log(`listening on http://localhost:${port}`));
const childProcess = require('child_process'); const path = require('path') module.exports = async function (params) { await createGitPullPromise() return await createPackPromise() } function createPackPromise(){ return new Promise((res, rej) => { const compile = childProcess.spawn('npm', ['run', 'build'], {cwd: path.resolve(__dirname, '../../fontend')}) compile.on('close', code => { // console.log(code) res(code) }) }) } function createGitPullPromise(){ return new Promise((res, rej) => { const compile = childProcess.spawn('git', ['pull'], {cwd: path.resolve(__dirname, '../../fontend')}) compile.on('close', code => { // console.log(code) res(code) }) }) }
child_process模塊,主要是用的child_process.spawn(),須要注意的是,這個函數只會建立異步進程,具體的API能夠參考官網。異步進程的話,不會阻塞主進程的執行,因此我backend/service/git-push.js
裏面用async function
來進行異步回調的控制。child_process模塊還提供了建立同步子進程的方法 child_process.spawnSync,瞭解nodejs比較多的同窗可能會發現,跟異步的方法相比,就是最後面加了個Sync
,嗯,也能夠這麼理解吧。
但願你們多瞭解下這個模塊,多動手操做下,能用到哪裏 留下了很是大的想象空間!node