From e974150bb32632e3b2123d039e8478dd492e4abb Mon Sep 17 00:00:00 2001 From: nuintun Date: Thu, 14 Jan 2016 10:06:49 +0800 Subject: [PATCH] update files --- bin/emulator.js | 15 ++++++++++++++ bin/thread.js | 52 +++++++++++++++++-------------------------------- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/bin/emulator.js b/bin/emulator.js index 40e125c..849c28a 100644 --- a/bin/emulator.js +++ b/bin/emulator.js @@ -14,15 +14,29 @@ var threadKill = require('./thread-kill'); */ function Emulator(task){ this.task = task; + this.thread = null; + this.connected = false; } Emulator.prototype = { start: function (){ + var context = this; + this.thread = spawn(this.task.command, { env: this.task.env, cwd: this.task.cwd }); + this.thread.stderr.on('data', function (){ + context.stop(); + }); + + this.thread.on('close', function (){ + context.stop(); + }); + + this.connected = true; + return this.thread; }, stop: function (){ @@ -35,6 +49,7 @@ Emulator.prototype = { }); context.thread = null; + context.connected = false; }); } } diff --git a/bin/thread.js b/bin/thread.js index 6831613..6577219 100644 --- a/bin/thread.js +++ b/bin/thread.js @@ -6,27 +6,11 @@ var path = require('path'); var ipc = require('ipc-main'); -var fork = require('child_process').fork; +var Emulator = require('./emulator'); // cache var threads = {}; -/** - * killThread - * @param name - */ -function killThread(name){ - var thread = threads[name]; - - if (thread && thread.connected) { - thread.send({ - action: 'stop' - }); - - delete threads[name]; - } -} - module.exports = { start: function (){ ipc.on('emulator', function (event, project, action){ @@ -45,37 +29,37 @@ module.exports = { env[item.name] = item.value; }); - thread = fork(path.join(__dirname, 'child-thread'), { - env: env + thread = new Emulator({ + env: env, + cwd: project.path, + command: project.command.value }); - thread.on('message', function (message){ - event.sender.send('emulator', message.event, message.project, message.data); + var stream = thread.start(); + + stream.stdout.on('data', function (data){ + event.sender.send('emulator', 'data', project, data.toString()); }); - thread.on('error', function (){ - killThread(project.name); + stream.stderr.on('data', function (error){ + event.sender.send('emulator', 'error', project, error.toString()); }); - delete project.env; + stream.on('close', function (signal){ + event.sender.send('emulator', 'close', project, signal.toString()); - thread.send({ - action: 'start', - project: project + delete threads[project.name]; }); threads[project.name] = thread; } else { - delete project.env; - - thread.send({ - action: 'start', - project: project - }); + thread.stop(); } break; case 'stop': - killThread(project.name); + if (thread) { + thread.stop(); + } break; } });