I'm just playing around with Node.js for the first time. I have the standard base server.js file:
var server = require('http').createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
console.log('Server started and listening...');
server.listen(1337, '127.0.0.1');
Now, what I'd like to know how to do is, given server, how can I dispose of the instance and start up a new instance? For example, here's my naive pseudocode:
function launchServer() {
var server = require('http').createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
console.log('Server started and listening...');
server.listen(1337, '127.0.0.1');
return server;
}
var server = launchServer();
require('fs').watchFile('server.js', function(curr, prev) {
console.log('Restarting server...');
server = null;
server = launchServer();
});
See what I'm trying to do here—reload the server.js file everytime I change it, as I play around and learn node.js?
I'm not necessarily interested in the "proper" way to do this or using a framework to do this; I'm interesting in learning the basics by doing things the hard, naive way first.
You can just close the server, wait for the callback, remove the server from the require cache then call your launch server method.
See: stackoverflow question: node.js require() cache - possible to invalidate?
and
NodeJS documentation: server.close([callback])
for more information.