From 792bccdd4e0ac716ba5fd8c4a0dd0333525b3911 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Wed, 24 May 2017 12:01:06 +0800 Subject: [PATCH] fix: should ignore getaddrinfo ENOTFOUND error (#22) closes https://github.com/node-modules/detect-port/issues/21 --- lib/detect-port.js | 4 ++++ package.json | 1 + test/detect-port.test.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/lib/detect-port.js b/lib/detect-port.js index 93fd628..0cf22c3 100644 --- a/lib/detect-port.js +++ b/lib/detect-port.js @@ -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); }); diff --git a/package.json b/package.json index 33f3d98..66d8060 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/test/detect-port.test.js b/test/detect-port.test.js index 39d19eb..8558add 100644 --- a/test/detect-port.test.js +++ b/test/detect-port.test.js @@ -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', () => { @@ -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(); @@ -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); @@ -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) => {