Using Node.js, if I write app.js as:
var commons = {
title: 'myTitle',
description: 'MyDesc',
menu: {
home: {
label: 'Home',
url: '/',
},
contacts: {
label: 'Contacts',
url: '/contacts'
}
}
}
console.log(commons);
I’ve this output…
{
title: 'myTitle',
description: 'MyDesc',
menu: {
home: {
label : 'Home',
url: '/'
},
contacts: {
label: 'Contacts',
url: '/contacts'
}
}
}
…and it works fine.
But, if I would load a variable in app.js from another file (in the same path)…
commons.js:
exports.commons = {
title: 'myTitle',
description: 'MyDesc',
menu: {
home: {
label: 'Home',
url: '/',
},
contacts: {
label: 'Contacts',
url: '/contacts'
}
}
}
app.js:
var commons = require('./commons');
console.log(commons);
I’ve as output:
commons: {
{
title: 'myTitle',
description: 'MyDesc',
menu: {
home: [Object],
contacts: [Object]
}
}
}
Why is this happening? How can I pass the variable across the two files correctly?
In a module,
exportsis an object with all the things that are exported when the module is required somewhere else. So by settingexports.commons = { ...you are basically setting thecommonsproperty of theexportsobject. This means that you nested your actual object in another object for the export.In your other module, you import then the whole
exportsobject usingcommons = require('./commons'). So your actualcommonsobject that you set is atcommons.commons.If you don’t want to nest the data in another object, you can just set the
exportsobject directly, usingmodule.exports:Then the import works as you expect it to.
The
[Object]in the output is, as pimvdb said, just somethingconsole.logdoes to not go too deep in the hierarchy. The data is still there, and you will probably see the contents just fine when you remove the first level as explained above.