Skip to content

Commit

Permalink
fix: should ignore getaddrinfo ENOTFOUND error (#22)
Browse files Browse the repository at this point in the history
closes #21
  • Loading branch information
fengmk2 authored May 24, 2017
1 parent e99c992 commit 792bccd
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/detect-port.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ function listen(port, hostname, callback) {
server.on('error', err => {
debug('listen %s:%s error: %s', hostname, port, err);
server.close();
if (err.code === 'ENOTFOUND') {
debug('ignore dns ENOTFOUND error, get free %s:%s', hostname, port);
return callback(null, port);
}
return callback(err);
});

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"egg-ci": "^1.1.0",
"eslint": "^3.13.1",
"eslint-config-egg": "^3.1.0",
"mm": "^2.1.0",
"pedding": "^1.1.0"
},
"scripts": {
Expand Down
28 changes: 28 additions & 0 deletions test/detect-port.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const assert = require('assert');
const net = require('net');
const pedding = require('pedding');
const address = require('address');
const mm = require('mm');
const dns = require('dns');
const detectPort = require('..');

describe('detect port test', () => {
Expand All @@ -12,6 +14,9 @@ describe('detect port test', () => {
done = pedding(12, done);
const server = new net.Server();
server.listen(3000, 'localhost', done);
server.on('error', err => {
console.error('listen localhost error:', err);
});
servers.push(server);

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

afterEach(mm.restore);

it('get random port', done => {
detectPort((_, port) => {
assert(port >= 1024 && port < 65535);
Expand All @@ -57,6 +64,27 @@ describe('detect port test', () => {
});
});

it('should listen next port 4001 when localhost is not binding', done => {
// https://github.com/nodejs/node/blob/6af72d4b037eba38d94395f57a03a498a2efef09/lib/net.js#L1463
// mock dns.lookup
mm(dns, '__rawLookup', dns.lookup);
mm(dns, 'lookup', (address, callback) => {
if (address !== 'localhost') {
return dns.__rawLookup(address, callback);
}
process.nextTick(() => {
const err = new Error(`getaddrinfo ENOTFOUND ${address}`);
err.code = 'ENOTFOUND';
callback(err);
});
});
const port = 4000;
detectPort(port, (_, realPort) => {
assert(realPort === 4001);
done();
});
});

it('work with listening next port 4001 because 4000 was listen by ' + address.ip(), done => {
const port = 4000;
detectPort(port, (_, realPort) => {
Expand Down

0 comments on commit 792bccd

Please sign in to comment.