Introduction to Detect-port
Detect-port is a powerful tool for identifying available ports on a machine, ensuring that your applications run smoothly without port conflicts. This guide provides comprehensive examples of its API along with code snippets.
Installation
npm install detect-port
Basic Usage
Check the availability of a specific port:
const detect = require('detect-port'); const port = 3000; detect(port, (err, _port) => { if (err) { console.log(err); } if (port == _port) { console.log(`port ${port} was not occupied`); } else { console.log(`port ${port} was occupied, try port ${_port}`); } });
Using Promises
const detect = require('detect-port'); (async () => { try { const _port = await detect(3000); console.log(`port 3000 was not occupied`); } catch (err) { console.log(err); } })();
Customized Port Range Detection
const detect = require('detect-port'); const portRange = [3000, 3005]; (async () => { for (let port of portRange) { try { const _port = await detect(port); if (port === _port) { console.log(`port ${port} was not occupied`); break; } } catch (err) { console.log(err); } } })();
Detect-port in an Application
Below is an example of an application using detect-port to find an available port to run an Express server:
const detect = require('detect-port'); const express = require('express'); const app = express(); (async () => { try { const port = await detect(3000); app.listen(port, () => { console.log(`Server is running on port ${port}`); }); } catch (err) { console.log(err); } })();
Using detect-port ensures that your application avoids common port conflicts, improving the reliability and user experience.
Conclusion
Detect-port is a crucial tool for developers aiming to ensure reliable port management in their applications. Whether you prefer callbacks or promises, detect-port has you covered. Implement it today for more robust and conflict-free executions.