var Q      = require('q'),
    spawn  = require('child_process').spawn,
    fs     = require('fs'),
    net    = require('net'),
    logger = require('winston'),
    mpdConfig = require(__dirname+'/mpd-config.js');

exports.create = function(config) {
  var mpdConf = mpdConfig.create(),
      instance = {};

  instance.port = mpdConf.port;

  function waitToBeOnline() {
    var deferred = Q.defer(),
        sock = new net.Socket();

    sock.setTimeout(2500);

    sock.on('connect', function() {
      logger.info('connected to '+instance.port);
      deferred.resolve();
    });

    sock.on('error', function(error) {
      logger.error('error for '+instance.port, error);

      setTimeout(function() {
        sock.connect(instance.port);
      }, 10);
    });

    sock.connect(instance.port);

    return deferred.promise;
  }

  function spawnMPD(fileName) {
    var deferred = Q.defer(),
        mpdProcess = spawn('/usr/local/bin/mpd', [fileName, '--no-daemon']);

    mpdProcess.on('close', function(code, signal) {
      logger.error('MPD Closed: ' + code);
    });

    mpdProcess.stdout.on('data', function(data) {
      logger.info('MPD: ' + data);
    });

    mpdProcess.stderr.on('data', function(data) {
      logger.warn('MPD: ' + data);
    });

    deferred.resolve();

    return deferred.promise;
  }

  instance.start = function() {
    return mpdConf.write(config).then(spawnMPD)
      .then(waitToBeOnline);
  };

  return instance;
};

@@ -151,24 +151,77 @@
 'winston'),%0A
+    waitForSocket = require('./wait-for-socket.js'),%0A
     mpdConfi
@@ -261,16 +261,16 @@
 g.js');%0A
-
 %0Aexports
@@ -427,362 +427,50 @@
     
-var deferred = Q.defer(),%0A        sock = new net.Socket();%0A%0A    sock.setTimeout(2500);%0A%0A    sock.on('connect', function() %7B%0A      logger.info('connected to '+instance.port);%0A      deferred.resolve();%0A    %7D);%0A%0A    sock.on('error', function(error) %7B%0A      logger.error('error for '+instance.port, error);%0A%0A      setTimeout(function() %7B%0A        sock.connect
+return waitForSocket%0A              .create
 (ins
@@ -484,94 +484,33 @@
 ort)
-;
 %0A      
-%7D, 10);%0A    %7D);%0A%0A    sock.connect(instance.port);%0A%0A    return deferred.promise
+        .connect()
 ;%0A  

Replace with tested wait-for-socket implementation