const spawn = require('child_process').spawn;
var events = require('events');
var eventEmitter = new events.EventEmitter();
var batchListener = function batchFinishListener(batchName) {
console.log('Finished : ' + batchName);
};
eventEmitter.addListener('batchFinish', batchListener);
function executeProject(batchFile) {
const bat = spawn('cmd.exe', ['/c', batchFile]);
bat.stdout.on('data', function (data) {
console.log(''+data);
});
bat.stderr.on('data', function (data) {
console.log(''+data);
});
bat.on('exit', (code, batchFile) => {
eventEmitter.emit('Finish', '' + batchFile);
console.log('Child exited with code ' + code);
});
}
在上面的代码中,在bat.on(exit, callback)
中我需要将变量batchFile传递给回调并将其传递给eventListener。怎么做?
修改:这适用于下面的修改
bat.on('exit', (code) => {
eventEmitter.emit('Finish', '' + batchFile);
console.log('Child exited with code ' + code);
});
答案 0 :(得分:0)
添加回调函数参数应该有帮助:
// ...update
function executeProject(batchFile, callback) {
const bat = spawn('cmd.exe', ['/c', batchFile]);
bat.stdout.on('data', (data) => console.log('' + data));
bat.stderr.on('data', (data) => console.log('' + data));
bat.on('error', callback); // Capture possible error
bat.on('exit', (code) => {
callback(null, code, batchFile);
});
}
// Usage example
executeProject(batchFile, (error, code, batchFile) => {
if (error) {
eventEmitter.emit('error', error);
} else {
eventEmitter.emit('something-happend', batchFile);
}
});
注意尽可能尝试不使用全局引用。因为它可以使你的代码单片而不是可重复使用。