Skip to content

Instantly share code, notes, and snippets.

@visnup
Last active May 17, 2019 11:57
Show Gist options
  • Save visnup/9801864 to your computer and use it in GitHub Desktop.
Save visnup/9801864 to your computer and use it in GitHub Desktop.
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