Skip to content

Commit 792bccd

Browse files
authored
fix: should ignore getaddrinfo ENOTFOUND error (#22)
closes #21
1 parent e99c992 commit 792bccd

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

lib/detect-port.js

+4
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ function listen(port, hostname, callback) {
7272
server.on('error', err => {
7373
debug('listen %s:%s error: %s', hostname, port, err);
7474
server.close();
75+
if (err.code === 'ENOTFOUND') {
76+
debug('ignore dns ENOTFOUND error, get free %s:%s', hostname, port);
77+
return callback(null, port);
78+
}
7579
return callback(err);
7680
});
7781

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"egg-ci": "^1.1.0",
2626
"eslint": "^3.13.1",
2727
"eslint-config-egg": "^3.1.0",
28+
"mm": "^2.1.0",
2829
"pedding": "^1.1.0"
2930
},
3031
"scripts": {

test/detect-port.test.js

+28
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ const assert = require('assert');
44
const net = require('net');
55
const pedding = require('pedding');
66
const address = require('address');
7+
const mm = require('mm');
8+
const dns = require('dns');
79
const detectPort = require('..');
810

911
describe('detect port test', () => {
@@ -12,6 +14,9 @@ describe('detect port test', () => {
1214
done = pedding(12, done);
1315
const server = new net.Server();
1416
server.listen(3000, 'localhost', done);
17+
server.on('error', err => {
18+
console.error('listen localhost error:', err);
19+
});
1520
servers.push(server);
1621

1722
const server2 = new net.Server();
@@ -34,6 +39,8 @@ describe('detect port test', () => {
3439
servers.forEach(server => server.close());
3540
});
3641

42+
afterEach(mm.restore);
43+
3744
it('get random port', done => {
3845
detectPort((_, port) => {
3946
assert(port >= 1024 && port < 65535);
@@ -57,6 +64,27 @@ describe('detect port test', () => {
5764
});
5865
});
5966

67+
it('should listen next port 4001 when localhost is not binding', done => {
68+
// https://github.com/nodejs/node/blob/6af72d4b037eba38d94395f57a03a498a2efef09/lib/net.js#L1463
69+
// mock dns.lookup
70+
mm(dns, '__rawLookup', dns.lookup);
71+
mm(dns, 'lookup', (address, callback) => {
72+
if (address !== 'localhost') {
73+
return dns.__rawLookup(address, callback);
74+
}
75+
process.nextTick(() => {
76+
const err = new Error(`getaddrinfo ENOTFOUND ${address}`);
77+
err.code = 'ENOTFOUND';
78+
callback(err);
79+
});
80+
});
81+
const port = 4000;
82+
detectPort(port, (_, realPort) => {
83+
assert(realPort === 4001);
84+
done();
85+
});
86+
});
87+
6088
it('work with listening next port 4001 because 4000 was listen by ' + address.ip(), done => {
6189
const port = 4000;
6290
detectPort(port, (_, realPort) => {

0 commit comments

Comments
 (0)