How to stop a node.js server without killing the process?


Question

Say a server is created like:

var net = require('net');

var server = net.createServer();
server.listen(32323, '127.0.0.1');

server.close(); // gives a "not running" error if there is IP in the listen statement

is there a way to stop it from node.js, e.g. without ending/killing the whole process?

Also, here's a more complicated example that doesn't stop regardless of the IP the server is bound to:

var net = require('net');

var server = net.createServer(function(socket) {
    socket.on('data', console.log);
    server.close();
});

server.listen(32323);

var socket = net.createConnection(32323);
socket.write('hi');
1
27
1/20/2012 4:55:01 PM

Accepted Answer

server.close

Do not call close before the "listening" event fires.

Either add a callback to listen or add an event manually

server.listen(port, host, function () { server.close(); });
// OR
server.on("listening", function () { server.close(); });
server.listen(port, host);

var net = require('net');

var server = net.createServer(function(socket) {
    socket.on('data', console.log);
    server.close();
});

server.listen(32323);

var socket = net.createConnection(32323);
// call end to make sure the socket closes
socket.end('hi');
24
2/26/2014 1:56:02 AM

Skipping to the 2nd, more realistic case: close the current connection before calling server.close:

var net = require('net')

var server = net.createServer(function(socket){
    socket.on('data', function(data){
        console.log(data.toString())
        socket.destroy()
        server.close()
    })
})

server.listen(32323)

Note that if you don't have any other server instances or activity going on in this process it will quit after closing server.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon