Welcome to Portastic: Efficient and Flexible Port Management
Portastic is a dynamic tool designed for developers to manage and query available ports efficiently within their systems. Whether you’re developing networked applications or just need to ensure that a port is free, Portastic offers an array of useful APIs to streamline your workflow. In this guide, we’ll introduce Portastic and dive into several API examples with practical code snippets.
Installation
Getting started with Portastic is simple. Install it via npm:
npm install portastic
API Overview
Portastic offers several key APIs that you can use to manage ports:
Finding an Open Port
Sometimes, you need to find an open port to bind a server. Use portastic.find
to locate available ports:
const portastic = require('portastic');
portastic.find({ min: 8000, max: 8050 }).then(ports => {
console.log('Available ports in range 8000-8050:', ports);
}).catch(err => {
console.error('Error finding ports:', err);
});
Checking Port Availability
To check if a specific port is available, you can use portastic.test
:
const port = 8080;
portastic.test(port).then(isOpen => {
if (isOpen) {
console.log(`Port ${port} is available.`);
} else {
console.log(`Port ${port} is already in use.`);
}
}).catch(err => {
console.error('Error testing port:', err);
});
Find Multiple Ports
Looking for multiple ports at once? Use portastic.findMultiple
:
portastic.findMultiple({ min: 8000, max: 9000, count: 5 }).then(ports => {
console.log('Found ports:', ports);
}).catch(err => {
console.error('Error finding multiple ports:', err);
});
App Example
Let’s create a simple app that finds an available port and starts an HTTP server:
const portastic = require('portastic');
const http = require('http');
portastic.find({ min: 3000, max: 4000 }).then(ports => {
if (ports.length > 0) {
const port = ports[0];
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(port, '127.0.0.1', () => {
console.log(`Server running at http://127.0.0.1:${port}/`);
});
} else {
console.log('No available ports found.');
}
}).catch(err => {
console.error('Error in finding ports:', err);
});
Conclusion
Portastic simplifies port management through its flexible APIs, allowing developers to find and test ports effortlessly. By incorporating Portastic into your projects, you can ensure reliable and efficient management of ports.
Happy coding with Portastic!
Hash: d3820a62b2e167ede67d6bb23d281305f91553a9c52c286c847df6dd5ba5bba8