Created
March 4, 2022 19:02
-
-
Save jeremygottfried/9622767fb475d50803a8e8aa1aee3e07 to your computer and use it in GitHub Desktop.
Check if a server is ready in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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