How to stop app that node.js express 'npm start'

后端 未结 16 2072
名媛妹妹
名媛妹妹 2020-12-07 11:00

You build node.js app with express v4.x then start your app by npm start. My question is how to stop the app? Is there npm stop?

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 11:11

    All the other solutions here are OS dependent. An independent solution for any OS uses socket.io as follows.

    package.json has two scripts:

    "scripts": {
      "start": "node server.js",
      "stop": "node server.stop.js"
    }
    

    server.js - Your usual express stuff lives here

    const express = require('express');
    const app = express();
    const server = http.createServer(app);
    server.listen(80, () => {
      console.log('HTTP server listening on port 80');
    });
    
    // Now for the socket.io stuff - NOTE THIS IS A RESTFUL HTTP SERVER
    // We are only using socket.io here to respond to the npmStop signal
    // To support IPC (Inter Process Communication) AKA RPC (Remote P.C.)
    
    const io = require('socket.io')(server);
    io.on('connection', (socketServer) => {
      socketServer.on('npmStop', () => {
        process.exit(0);
      });
    });
    

    server.stop.js

    const io = require('socket.io-client');
    const socketClient = io.connect('http://localhost'); // Specify port if your express server is not using default port 80
    
    socketClient.on('connect', () => {
      socketClient.emit('npmStop');
      setTimeout(() => {
        process.exit(0);
      }, 1000);
    });
    

    Test it out

    npm start (to start your server as usual)

    npm stop (this will now stop your running server)

    The above code has not been tested (it is a cut down version of my code, my code does work) but hopefully it works as is. Either way, it provides the general direction to take if you want to use socket.io to stop your server.

提交回复
热议问题