|
| 1 | +/* ================================================================ |
| 2 | + * detect-port by xdf(xudafeng[at]126.com) |
| 3 | + * |
| 4 | + * first created at : Tue Mar 17 2015 00:16:10 GMT+0800 (CST) |
| 5 | + * |
| 6 | + * ================================================================ |
| 7 | + * Copyright xdf |
| 8 | + * |
| 9 | + * Licensed under the MIT License |
| 10 | + * You may not use this file except in compliance with the License. |
| 11 | + * |
| 12 | + * ================================================================ */ |
| 13 | + |
| 14 | +// We are forking this temporarily to resolve |
| 15 | +// https://github.com/facebookincubator/create-react-app/issues/302. |
| 16 | + |
| 17 | +// We can replace this fork with `detect-port` package when this is merged: |
| 18 | +// https://github.com/xudafeng/detect-port/pull/4. |
| 19 | + |
| 20 | +'use strict'; |
| 21 | + |
| 22 | +var net = require('net'); |
| 23 | + |
| 24 | +var inject = function(port) { |
| 25 | + var options = global.__detect ? global.__detect.options : {}; |
| 26 | + |
| 27 | + if (options.verbose) { |
| 28 | + console.log('port %d was occupied', port); |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +function detect(port, fn) { |
| 33 | + |
| 34 | + var _detect = function(port) { |
| 35 | + return new Promise(function(resolve, reject) { |
| 36 | + var socket = new net.Socket(); |
| 37 | + socket.once('error', function() { |
| 38 | + socket.removeAllListeners('connect'); |
| 39 | + socket.removeAllListeners('error'); |
| 40 | + socket.end(); |
| 41 | + socket.destroy(); |
| 42 | + socket.unref(); |
| 43 | + var server = new net.Server(); |
| 44 | + server.on('error', function() { |
| 45 | + inject(port); |
| 46 | + port++; |
| 47 | + resolve(_detect(port)); |
| 48 | + }); |
| 49 | + |
| 50 | + server.listen(port, function() { |
| 51 | + server.once('close', function() { |
| 52 | + resolve(port); |
| 53 | + }); |
| 54 | + server.close(); |
| 55 | + }); |
| 56 | + }); |
| 57 | + socket.once('connect', function() { |
| 58 | + inject(port); |
| 59 | + port++; |
| 60 | + resolve(_detect(port)); |
| 61 | + socket.removeAllListeners('connect'); |
| 62 | + socket.removeAllListeners('error'); |
| 63 | + socket.end(); |
| 64 | + socket.destroy(); |
| 65 | + socket.unref(); |
| 66 | + }); |
| 67 | + socket.connect({ |
| 68 | + port: port |
| 69 | + }); |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + var _detect_with_cb = function(_fn) { |
| 74 | + _detect(port) |
| 75 | + .then(function(result) { |
| 76 | + _fn(null, result); |
| 77 | + }) |
| 78 | + .catch(function(e) { |
| 79 | + _fn(e); |
| 80 | + }); |
| 81 | + }; |
| 82 | + |
| 83 | + return fn ? _detect_with_cb(fn) : _detect(port); |
| 84 | +} |
| 85 | + |
| 86 | +module.exports = detect; |
0 commit comments