update files

This commit is contained in:
nuintun 2016-01-14 10:06:49 +08:00
parent bf76db01b9
commit e974150bb3
2 changed files with 33 additions and 34 deletions

View File

@ -14,15 +14,29 @@ var threadKill = require('./thread-kill');
*/ */
function Emulator(task){ function Emulator(task){
this.task = task; this.task = task;
this.thread = null;
this.connected = false;
} }
Emulator.prototype = { Emulator.prototype = {
start: function (){ start: function (){
var context = this;
this.thread = spawn(this.task.command, { this.thread = spawn(this.task.command, {
env: this.task.env, env: this.task.env,
cwd: this.task.cwd 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; return this.thread;
}, },
stop: function (){ stop: function (){
@ -35,6 +49,7 @@ Emulator.prototype = {
}); });
context.thread = null; context.thread = null;
context.connected = false;
}); });
} }
} }

View File

@ -6,27 +6,11 @@
var path = require('path'); var path = require('path');
var ipc = require('ipc-main'); var ipc = require('ipc-main');
var fork = require('child_process').fork; var Emulator = require('./emulator');
// cache // cache
var threads = {}; 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 = { module.exports = {
start: function (){ start: function (){
ipc.on('emulator', function (event, project, action){ ipc.on('emulator', function (event, project, action){
@ -45,37 +29,37 @@ module.exports = {
env[item.name] = item.value; env[item.name] = item.value;
}); });
thread = fork(path.join(__dirname, 'child-thread'), { thread = new Emulator({
env: env env: env,
cwd: project.path,
command: project.command.value
}); });
thread.on('message', function (message){ var stream = thread.start();
event.sender.send('emulator', message.event, message.project, message.data);
stream.stdout.on('data', function (data){
event.sender.send('emulator', 'data', project, data.toString());
}); });
thread.on('error', function (){ stream.stderr.on('data', function (error){
killThread(project.name); 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({ delete threads[project.name];
action: 'start',
project: project
}); });
threads[project.name] = thread; threads[project.name] = thread;
} else { } else {
delete project.env; thread.stop();
thread.send({
action: 'start',
project: project
});
} }
break; break;
case 'stop': case 'stop':
killThread(project.name); if (thread) {
thread.stop();
}
break; break;
} }
}); });