0
# Port Finding
1
2
Core port discovery functionality for finding single or multiple available ports with configurable host and range options.
3
4
## Capabilities
5
6
### Get Port Function
7
8
Finds and returns an unbound port on the current machine. Supports both callback and Promise-based usage.
9
10
```javascript { .api }
11
/**
12
* Responds with a unbound port on the current machine
13
* @param {PortFinderOptions} [options] - Port search options
14
* @param {function} [callback] - Callback function (err, port) => void
15
* @returns {Promise<number>} Promise resolving to available port (when no callback provided)
16
*/
17
function getPort(options?: PortFinderOptions): Promise<number>;
18
function getPort(callback: (err: Error, port: number) => void): void;
19
function getPort(options: PortFinderOptions, callback: (err: Error, port: number) => void): void;
20
```
21
22
**Usage Examples:**
23
24
```javascript
25
const portfinder = require('portfinder');
26
27
// Basic usage with callback
28
portfinder.getPort(function (err, port) {
29
if (err) throw err;
30
console.log('Available port:', port); // e.g., 8000
31
});
32
33
// Promise-based usage
34
portfinder.getPortPromise()
35
.then((port) => {
36
console.log('Available port:', port);
37
})
38
.catch((err) => {
39
console.error('Error finding port:', err);
40
});
41
42
// With options - callback style
43
portfinder.getPort({
44
port: 3000,
45
stopPort: 3010,
46
host: 'localhost'
47
}, function(err, port) {
48
if (err) throw err;
49
console.log('Port found:', port); // between 3000-3010 on localhost
50
});
51
52
// With options - Promise style
53
portfinder.getPort({
54
port: 8080,
55
host: '127.0.0.1'
56
})
57
.then(port => {
58
console.log('Port on 127.0.0.1:', port);
59
});
60
```
61
62
### Get Port Promise Function
63
64
Promise-based version of getPort (alias for getPort without callback).
65
66
```javascript { .api }
67
/**
68
* Responds a promise of an unbound port on the current machine
69
* @param {PortFinderOptions} [options] - Port search options
70
* @returns {Promise<number>} Promise resolving to available port
71
*/
72
function getPortPromise(options?: PortFinderOptions): Promise<number>;
73
```
74
75
**Usage Example:**
76
77
```javascript
78
const portfinder = require('portfinder');
79
80
// Equivalent to getPort without callback
81
const port = await portfinder.getPortPromise({
82
port: 4000,
83
stopPort: 5000
84
});
85
console.log('Found port:', port);
86
```
87
88
### Get Ports Function
89
90
Finds and returns an array of unbound ports on the current machine.
91
92
```javascript { .api }
93
/**
94
* Responds with an array of unbound ports on the current machine
95
* @param {number} count - The number of ports to find
96
* @param {PortFinderOptions} [options] - Port search options
97
* @param {function} [callback] - Callback function (err, ports) => void
98
* @returns {Promise<number[]>} Promise resolving to array of available ports (when no callback provided)
99
*/
100
function getPorts(count: number, options?: PortFinderOptions): Promise<number[]>;
101
function getPorts(count: number, callback: (err: Error, ports: number[]) => void): void;
102
function getPorts(count: number, options: PortFinderOptions, callback: (err: Error, ports: number[]) => void): void;
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
const portfinder = require('portfinder');
109
110
// Find 3 consecutive ports - callback style
111
portfinder.getPorts(3, function(err, ports) {
112
if (err) throw err;
113
console.log('Available ports:', ports); // e.g., [8000, 8001, 8002]
114
});
115
116
// Find 5 ports with options - Promise style
117
portfinder.getPorts(5, {
118
port: 9000,
119
stopPort: 9100
120
})
121
.then(ports => {
122
console.log('5 ports found:', ports); // e.g., [9000, 9001, 9002, 9003, 9004]
123
});
124
125
// Find 2 ports on specific host
126
portfinder.getPorts(2, {
127
host: '0.0.0.0',
128
port: 3000
129
}, function(err, ports) {
130
console.log('Ports on all interfaces:', ports);
131
});
132
```
133
134
### Get Ports Promise Function
135
136
Promise-based version of getPorts (alias for getPorts without callback).
137
138
```javascript { .api }
139
/**
140
* Responds a promise that resolves to an array of unbound ports on the current machine
141
* @param {number} count - The number of ports to find
142
* @param {PortFinderOptions} [options] - Port search options
143
* @returns {Promise<number[]>} Promise resolving to array of available ports
144
*/
145
function getPortsPromise(count: number, options?: PortFinderOptions): Promise<number[]>;
146
```
147
148
**Usage Example:**
149
150
```javascript
151
const portfinder = require('portfinder');
152
153
// Equivalent to getPorts without callback
154
const ports = await portfinder.getPortsPromise(4, {
155
port: 7000,
156
host: 'localhost'
157
});
158
console.log('Found ports:', ports);
159
```
160
161
### Next Port Function
162
163
Gets the next port in sequence from the specified port (simply port + 1).
164
165
```javascript { .api }
166
/**
167
* Gets the next port in sequence from the specified port
168
* @param {number} port - Port to increment from
169
* @returns {number} Next port (port + 1)
170
*/
171
function nextPort(port: number): number;
172
```
173
174
**Usage Example:**
175
176
```javascript
177
const portfinder = require('portfinder');
178
179
const currentPort = 8000;
180
const nextPort = portfinder.nextPort(currentPort);
181
console.log('Next port:', nextPort); // 8001
182
183
// Useful for manual port iteration
184
let testPort = 3000;
185
while (testPort < 3010) {
186
// Test port availability logic here
187
testPort = portfinder.nextPort(testPort);
188
}
189
```
190
191
## Options Interface
192
193
```javascript { .api }
194
/**
195
* Options for port finding operations
196
*/
197
interface PortFinderOptions {
198
/**
199
* Host to find available port on
200
* If not specified, tests all available network interfaces
201
*/
202
host?: string;
203
204
/**
205
* Minimum port (takes precedence over global basePort)
206
* Port search will start from this value
207
*/
208
port?: number;
209
210
/**
211
* Search start port (equals port when not provided)
212
* This exists because getPort mutates port state in recursive calls
213
* and doesn't have a way to retrieve beginning port while searching
214
*/
215
startPort?: number;
216
217
/**
218
* Maximum port (takes precedence over global highestPort)
219
* Port search will not exceed this value
220
*/
221
stopPort?: number;
222
}
223
```
224
225
## Advanced Usage Patterns
226
227
### Testing Multiple Hosts
228
229
```javascript
230
const portfinder = require('portfinder');
231
232
const hosts = ['127.0.0.1', '0.0.0.0', 'localhost'];
233
const promises = hosts.map(host =>
234
portfinder.getPortPromise({ port: 8000, host })
235
.then(port => ({ host, port }))
236
.catch(err => ({ host, error: err.message }))
237
);
238
239
Promise.all(promises).then(results => {
240
console.log('Port availability by host:', results);
241
});
242
```
243
244
### Port Range Allocation
245
246
```javascript
247
const portfinder = require('portfinder');
248
249
// Allocate ports for microservices
250
async function allocateServicePorts() {
251
const services = ['api', 'auth', 'cache', 'db'];
252
const basePorts = [8000, 8100, 8200, 8300];
253
254
const allocations = await Promise.all(
255
services.map(async (service, index) => {
256
const port = await portfinder.getPortPromise({
257
port: basePorts[index],
258
stopPort: basePorts[index] + 50
259
});
260
return { service, port };
261
})
262
);
263
264
return allocations;
265
}
266
267
allocateServicePorts().then(allocations => {
268
console.log('Service port allocations:', allocations);
269
// e.g., [
270
// { service: 'api', port: 8000 },
271
// { service: 'auth', port: 8100 },
272
// { service: 'cache', port: 8201 },
273
// { service: 'db', port: 8300 }
274
// ]
275
});
276
```
277
278
### Error Recovery
279
280
```javascript
281
const portfinder = require('portfinder');
282
283
async function findPortWithFallback(preferredPort) {
284
try {
285
// Try preferred port first
286
return await portfinder.getPortPromise({
287
port: preferredPort,
288
stopPort: preferredPort
289
});
290
} catch (err) {
291
console.log(`Port ${preferredPort} not available, finding alternative...`);
292
293
// Fall back to range search
294
return await portfinder.getPortPromise({
295
port: preferredPort,
296
stopPort: preferredPort + 100
297
});
298
}
299
}
300
301
findPortWithFallback(3000).then(port => {
302
console.log('Using port:', port);
303
});
304
```