I'm working on an application using Node.js and ExpressJS and I'm a beginner on this environment. I have the basic need of logging the entire or partial res.locals
's content in my console for debugging.
I've tried this :
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));
I'm searching for a kind of Perl's Data::Dumper, but it seems that I miss the point somewhere because it should be a very basic task...
Edit : I know this is maybe not specifically an ExpressJS or Node.js problem but much more a JS vars scope problem...
Note for people who would read this in 2018: don't use var
, use let
and const
.
Try using the eyespect
module instead of console.log
. It prints things in a way that is easier to work with.
npm install -S eyespect
When you assign foo_data inside the for loop, are you doing anything asynchronously? That could be a reason why things are not working as you expect
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));