当前位置: 首页 > 后端技术 > Node.js

nodejs最酷的模块——child_process——子进程

时间:2023-04-03 18:47:18 Node.js

什么是child_processchild_process模块??是nodejs的子进程模块,可以用来创建子进程,执行一些任务。要执行什么任务?shell命令你懂的,有了child_process模块??,就可以在js中直接调用shell命令,完成一些很酷的操作!!比如GitHub、码云等git代码托管站点都会有webhook功能。当有新代码推送时,服务端可以开启一个接口接受webhook请求,执行gitpull、npmrunbuild等命令,从而达到自动化部署的目的!这是一个小的演示目录结构。前端简单的使用vue-cli脚手架新建一个项目。后端使用快递。执行shell的方法。backend/server.jsbackend/server.js注意先安装几个依赖:express和body-parserexpress是主角,不用多说,body-parser就是用来解析post请求的参数的。constexpress=require('快递');constapp=express();constport=process.env.PORT||8080;constwww=process.env.WWW||'./fontend/dist';varbodyParser=require('body-parser')//格式化body数据app.use(bodyParser.urlencoded({extended:false}));//body解析器插件配置app.use(bodyParser.json());//body解析器插件配置constgitPush=require('./service/git-push')//引入写服务app.post('/api/git_hook',async(req,res)=>{//监听这个接口if(req.body.password!=='666'){//在这里查看post请求的密码res.send('wrongpassword')return}constcode=awaitgitPush()res.send('helloworld'+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(`监听http://localhost:${port}`));backend/service/git-push.jsconstchildProcess=require('child_process');constpath=require('path')module.exports=asyncfunction(params){等待createGitPullPromise()returnawaitcreatePackPromise()}functioncreatePackPromise(){returnnewPromise((res,rej)=>{constcompile=childProcess.spawn('npm',['run','build'],{cwd:path.resolve(__dirname,'../../fontend')})compile.on('close',code=>{//console.log(code)res(code)})})}functioncreateGitPullPromise(){returnnewPromise((res,rej)=>{constcompile=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函数来控制异步回调。child_process模块还提供了child_process.spawnSync方法来创建同步子进程。对nodejs比较了解的同学可能会发现,和异步方式相比,在最后添加了Sync。嗯,可以这样理解。希望大家多多了解这个模块,多动手操作,用在什么地方都有很大的想象空间!