Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Listen on a TCP port or a UNIX socket file in node.js. Handle EADDRINUSE for the socket file by deleting it and re-listening.
var fs = require('fs')
, net = require('net')
, http = require('http')
, port = process.env.PORT;
var app = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
};
var server = http.createServer(app).listen(port, function() {
require('util').log("Listening on " + port);
// downgrade process user to owner of this file
return fs.stat(__filename, function(err, stats) {
if (err) throw err;
return process.setuid(stats.uid);
});
});
// port is a UNIX socket file
if (isNaN(parseInt(port))) {
server.on('listening', function() {
// set permissions
return fs.chmod(port, 0777);
});
// double-check EADDRINUSE
server.on('error', function(e) {
if (e.code !== 'EADDRINUSE') throw e;
net.connect({ path: port }, function() {
// really in use: re-throw
throw e;
}).on('error', function(e) {
if (e.code !== 'ECONNREFUSED') throw e;
// not in use: delete it and re-listen
fs.unlinkSync(port);
server.listen(port);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment