Skip to content

Instantly share code, notes, and snippets.

@ericvicenti
Created December 5, 2018 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericvicenti/876e2df1103232f1fe6781c927e0eb63 to your computer and use it in GitHub Desktop.
Save ericvicenti/876e2df1103232f1fe6781c927e0eb63 to your computer and use it in GitHub Desktop.
Start server gracefully on unix socket
const fs = require('fs');
const net = require('net');
async function isSocketInUse(socketPath) {
return new Promise((resolve, reject) => {
const clientSocket = new net.Socket();
clientSocket.on('error', e => {
if (e.code === 'ECONNREFUSED') {
resolve(false);
} else {
reject(e);
}
});
clientSocket.connect(
{ path: socketPath },
() => {
clientSocket.unref();
resolve(true);
}
);
});
}
async function listen(server, listenLocation) {
return new Promise((resolve, reject) => {
server.listen(listenLocation, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
export default async function startServer(server, listenLocation) {
try {
await listen(server, listenLocation);
} catch (e) {
if (e.code !== 'EADDRINUSE') {
throw e;
}
if (await isSocketInUse(listenLocation)) {
throw e;
}
await fs.unlink(listenLocation);
await listen(server, listenLocation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment