1

我正在使用 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 的 Data::Dumper,但似乎我在某处错过了重点,因为它应该是一项非常基本的任务......

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

2018 年阅读本文的人请注意:不要使用var、使用letconst

4

1 回答 1

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));
于 2013-04-10T12:49:18.747 回答