Skip to content

Instantly share code, notes, and snippets.

@jeremygottfried
Created March 4, 2022 19:02
Show Gist options
  • Save jeremygottfried/9622767fb475d50803a8e8aa1aee3e07 to your computer and use it in GitHub Desktop.
Save jeremygottfried/9622767fb475d50803a8e8aa1aee3e07 to your computer and use it in GitHub Desktop.
Check if a server is ready in node.js
import http from 'http';
function delay(time) {
return new Promise(((resolve) => {
setTimeout(resolve, time);
}));
}
function serverReady() {
return new Promise(((resolve) => {
async function checkReady() {
process.stdout.write('...');
await delay(500);
const req = http.get({
hostname: 'localhost',
port: parseInt(process.env.port),
path: '/',
}, (res) => {
if (res.statusCode === 200) {
resolve();
} else {
return checkReady();
}
});
req.on('error', () => checkReady());
}
checkReady();
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment