1. const {cpus}=require("os")
    2. const cluster=require("cluster")
    3. const cpusLength=cpus().length;
    4. if(cluster.isMaster){
    5. let worker;
    6. for(let i=0;i<cpusLength;i++){
    7. worker= cluster.fork()
    8. worker.on('exit',()=>{
    9. cluster.fork()
    10. })
    11. worker.on("listening",address=>{
    12. console.log(`${address.port}端口启动成功,进程id:${worker.process.pid}`)
    13. })
    14. }
    15. }else{
    16. require("./server/app")
    17. }
    1. 子进程
    2. const koa=require("koa")
    3. const app=new koa()
    4. const path=require("path")
    5. const router=require("./router/index")
    6. const bodyParser=require("koa-bodyparser")
    7. const koaViews=require("koa-views")
    8. const views=path.join(__dirname,"./views")
    9. app.use(bodyParser())
    10. app.use(require("koa-static")(__dirname+"./public"))
    11. app.use(koaViews(views,{
    12. extension:'html'
    13. }))
    14. app.use(router.routes(),router.allowedMethods())
    15. const PORT=process.env.PORT||8080
    16. app.listen(PORT)
    17. module.exports=app