network.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Utilities: A classic collection of JavaScript utilities
  3. * Copyright 2112 Matthew Eernisse ([email protected])
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. var network
  19. , net = require('net');
  20. /**
  21. @name network
  22. @namespace network
  23. */
  24. network = new (function () {
  25. /**
  26. @name network#isPortOpen
  27. @public
  28. @function
  29. @description Checks if the given port in the given host is open
  30. @param {Number} port number
  31. @param {String} host
  32. @param {Function} callback Callback function -- should be in the format
  33. of function(err, result) {}
  34. */
  35. this.isPortOpen = function (port, host, callback) {
  36. if (typeof host === 'function' && !callback) {
  37. callback = host;
  38. host = 'localhost';
  39. }
  40. var isOpen = false
  41. , connection
  42. , error;
  43. connection = net.createConnection(port, host, function () {
  44. isOpen = true;
  45. connection.end();
  46. });
  47. connection.on('error', function (err) {
  48. // We ignore 'ECONNREFUSED' as it simply indicates the port isn't open.
  49. // Anything else is reported
  50. if(err.code !== 'ECONNREFUSED') {
  51. error = err;
  52. }
  53. });
  54. connection.setTimeout(400, function () {
  55. connection.end();
  56. });
  57. connection.on('close', function () {
  58. callback && callback(error, isOpen);
  59. });
  60. };
  61. })();
  62. module.exports = network;