diff --git a/src/cli/index.js b/src/cli/index.js index 93ef6ed091..fe5cd6f353 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -268,26 +268,28 @@ const runEventuallyWithNetwork = (mutexPort: ?string): Promise => { port: +mutexPort || constants.SINGLE_INSTANCE_PORT, }; - const clients = []; - const server = net.createServer((client: net$Socket) => { - clients.push(client); - }); + const server = net.createServer(); server.on('error', () => { - // another yarnn instance exists, let's connect to it to know when it dies. + // another Yarn instance exists, let's connect to it to know when it dies. reporter.warn(reporter.lang('waitingInstance')); const socket = net.createConnection(connectionOptions); socket - .on('data', () => { - // the server has informed us he's going to die soon™. - socket.unref(); // let it die - process.nextTick(() => { - ok(runEventuallyWithNetwork(mutexPort)); - }); + .on('connect', () => { + // Allow the program to exit if this is the only active server in the event system. + socket.unref(); + }) + .on('close', (hadError?: boolean) => { + // the `close` event gets always called after the `error` event + if (!hadError) { + process.nextTick(() => { + ok(runEventuallyWithNetwork(mutexPort)); + }); + } }) .on('error', () => { - // No server to listen to ? :O let's retry to become the next server then. + // No server to listen to ? Let's retry to become the next server then. process.nextTick(() => { ok(runEventuallyWithNetwork(mutexPort)); }); @@ -295,9 +297,6 @@ const runEventuallyWithNetwork = (mutexPort: ?string): Promise => { }); const onServerEnd = (): Promise => { - clients.forEach((client) => { - client.write('closing. kthanx, bye.'); - }); server.close(); return Promise.resolve(); }; @@ -385,7 +384,7 @@ config.init({ } }).catch((err: Error) => { reporter.verbose(err.stack); - + if (err instanceof MessageError) { reporter.error(err.message); } else {