节点fork子进程并得到它的错误

时间:2015-04-07 01:28:59

标签: javascript node.js

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

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 个答案:

答案 0 :(得分: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 }会把事情搞砸了