如何使用ExpressJS和Nodejs在控制台中记录res.locals内容以进行调试?

时间:2013-04-10 11:30:21

标签: javascript node.js debugging express data-dumper

我正在使用Node.js和ExpressJS开发应用程序,而且我是这个环境的初学者。我基本需要在我的控制台中记录整个或部分res.locals的内容以进行调试。

我试过这个:

var foo_route = function(req, res){

    var foo_data = [];

    for (var i = 0; i < data.response.foo.length; i++) {

        // Here complex data management, not interesting in our case
        foo_data = // Bla bla ...

        // OK. This displays my object content
        console.log(foo_data);

    }

    // Seems because my misunderstanding of JS scopes, foo_data is still == []
    res.locals.data = foo_data;

    // Nothing. Both of these two solutions display nothing
    console.log(res.locals.data);
    console.log(JSON.stringify(res.locals.data, null, 2));

我正在寻找一种Perl's Data::Dumper,但似乎我在某处错过了这一点,因为它应该是一项非常基本的任务......

编辑:我知道这可能不是特定的ExpressJS或Node.js问题,而是JS vars范围问题......

请注意在2018年阅读此内容的人:请勿使用var,请使用letconst

1 个答案:

答案 0 :(得分:2)

尝试使用eyespect模块而不是console.log。它以更容易使用的方式打印东西。

npm install -S eyespect

当你在for循环中分配foo_data时,你是在做异步吗?这可能是事情没有按预期工作的原因

var foo_route = function(req, res){

    var foo_data = [];
    // what is data here? Also var i should technically be declared at the top of the function
    for (var i = 0; i < data.response.foo.length; i++) {

        // Here complex data management, not interesting in our case
        foo_data = ...

        // OK. This displays my object content
        console.log(foo_data);

    }
    // does this print anything interesting?
    inspect(foo_data, 'foo data outside the loop')
    inspect(res.locals, 'res.locals')
    // Seems because my misunderstanding of JS scopes, foo_data is still == []
    res.locals.data = foo_data;
    inspect(res.locals.data, 'res.locals.data')    

    // Nothing. Both of these two solutions display nothing
    console.log(res.locals.data);
    console.log(JSON.stringify(res.locals.data, null, 2));