npm i @fjrodafo/free-port
// Import the module
const { findAvailablePort } = require('@fjrodafo/free-port');
// It will find an available port in case port 3000 is busy
findAvailablePort(3000).then(port => {
server.listen(port, () => {
console.log(`Server listening on port http://localhost:${port}`);
});
});
// You can create an environment variable for advanced use
const desiredPort = process.env.PORT ?? 3000;
findAvailablePort(desiredPort).then(port => {
server.listen(port, () => {
console.log(`Server listening on port http://localhost:${port}`);
});
});
Full repository on github/gitlab.
Visit the npm package website here.