2015-04-07 52 views
0

我能够fork一个子进程,但我有问题看到该文件中发生了什么错误,并且我知道该文件有错误,因为我创建了一个没有关闭}所以应该发生错误。使用下面的代码,我得到什么(在控制台和/或浏览器):节点fork子进程,并得到它的错误

var child = require('child_process').fork(full_path, [], { 
    silent: true, 
}); 

// Tried both of these and nothing gets displayed 
child.stdout.on('error', function(data){ 
    res.write(data); 
    console.log(data); 
}); 
child.stderr.on('error', function(data){ 
    res.write(data); 
    console.log(data); 
}); 

这里是子进程:

var sys = require('sys'); 
var mustache = require('mustache'); 
var template = require('./templates/mypage.html'); 

sys.puts(template); 

var view = { 
    "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] 
; // Forced error here with no closing "}" 

var html = mustache.to_html(template, view); 
sys.puts(html); 

什么我需要做的,以显示错误?我做错了什么?

编辑

完整的脚本:

var sys = require('sys'); 
var config = require('./server.json'); 
var url = require('url'); 
var http = require('http'); 

function handleRequest(req, res){ 
    var full_path = ""; 

    for(var i in config){ 
     var domain = config[i].server; 
     if(req.headers.host === domain){ 
      var info = url.parse(req.url); 
      full_path = config[i].root + info.pathname; 
     } 
    } 

    console.log("Page: " + full_path); 

    if(full_path != ""){ 
     var child = require('child_process').fork(full_path, [], { 
      silent: true, 
     }); 
     child.stdout.on('data', function(data){ 
      res.write(data); 
     }); 
     child.stdout.on('error', function(data){ 
      res.write(data); 
      console.log(data); 
     }); 
     child.stderr.on('error', function(data){ 
      res.write(data); 
      console.log(data); 
     }); 
     child.stdout.on('end', function(){ 
      res.end(); 
     }); 
    }else{ 
     res.end(); 
    } 
} 

var server = http.createServer(handleRequest); 
server.listen(3000, function(err){ 
    console.log(err || 'Server listening on 3000'); 
}); 
+1

'child.stderr'? – zerkms

+0

我也试过了,它不起作用 –

+0

什么“不起作用”是什么意思?你试过什么? – zerkms

回答

0

默认情况下,所有的输入/输出又回到了父母。

鉴于parent.js

var fork = require('child_process').fork; 
var child = fork('./child'); 

输出和child.js错误回到父母

setInterval(function() { 
    console.log('I am here') 
}, 1000); 
setTimeout(function() { 
    throw new Error('oops') 
}, 5000); 

像@Plato说,{ silent: true }是不会关的事情了

+0

我不明白你是如何处理错误的...... –

+0

节点之间没有传递错误,孩子只是写给父母stderr(当它记录未捕获的异常时)。孩子应该处理它自己的错误。如果您想在节点之间进行通信,请查看[消息](https://nodejs.org/api/child_process.html#child_process_event_message) – lyjackal