【问题标题】:How to log res.locals content in console with ExpressJS and Nodejs for debugging?如何使用 ExpressJS 和 Nodejs 在控制台中记录 res.locals 内容以进行调试?
【发布时间】:2013-04-10 11:30:20
【问题描述】:

我正在使用 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

【问题讨论】:

  • 如果console.log(res.locals.data); 显示注释,则它必须为空/未定义。我们可以看到更多代码吗?你在哪里做可能很重要。
  • @UpTheCreek,是的,你是对的。我的问题似乎更多地与变量范围有关,不是吗?我已经编辑了示例代码。
  • 我认为您确定foo_data 值的方式实际上非常有趣,因为这可能是您的console.log 为空的原因。

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


【解决方案1】:

尝试使用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));

【讨论】:

  • 全面披露,eyespect 是eyes.js github.com/cloudhead/eyes.js 的一个分支,但具有不同的默认颜色。
  • 我试用了你的 Eyespect 模块,它是一款了不起的软件,与 Perl 的 Data::Printer(彩色 Data::Dumper)完全一样。我们会在工作中使用,调试的时候眼睛会很甜!
猜你喜欢
  • 2017-11-06
  • 2016-04-24
  • 1970-01-01
  • 2021-03-08
  • 2023-03-23
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多