Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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'); 
like image 636
Fluffy Avatar asked Jan 20 '12 14:01

Fluffy


People also ask

How do I shutdown a npm server?

To stop a running npm process, press CTRL + C or close the shell window.

How do I quit a live server?

Shortcuts to Start/Stop Server Open the Command Pallete by pressing F1 or ctrl+shift+P and type Live Server: Open With Live Server to start a server or type Live Server: Stop Live Server to stop a server.

How do I exit node in terminal?

Press CTRL+ c (even on a Mac, especially on a Mac!), or just call the process. exit() method to exit from the Node console. or even simpler you can just type . exit .


1 Answers

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'); 
like image 162
Raynos Avatar answered Oct 05 '22 17:10

Raynos