Last active
May 13, 2020 04:45
-
-
Save cahilfoley/3b9439cafb63add48787db89aad6662f to your computer and use it in GitHub Desktop.
Async function to check if port is available 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
/** | |
* This is a modern rewrite of this gist https://gist.github.com/timoxley/1689041 using promises | |
*/ | |
import { createServer } from 'net' | |
export async function isPortAvailable(port: number): Promise<boolean> { | |
return await new Promise((resolve, reject) => { | |
const testServer = createServer() | |
testServer.once('error', (err) => { | |
if (err.code === 'EADDRINUSE') { | |
// Port is not free | |
return resolve(false) | |
} else { | |
// Some other error happened | |
reject(err) | |
} | |
}) | |
// If it starts then the port is free | |
testServer.once('listening', () => { | |
testServer.once('close', () => resolve(true)) | |
testServer.close() | |
}) | |
testServer.listen(port) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment