Dan Savage Dan Savage - 1 month ago 6x
Node.js Question

Why is it console.log will sometimes print undefined for a variable which has been exported?

So I'm working in node.js (beginner) and I'm trying to use variables which are in a different script. What I've found is that sometimes the variable comes back as undefined. For instance:

//Doesnt like this
var peaches = 'Peaches';

// Likes
exports.peaches = 'Peaches'

Now, It I require this script, I find that if I use the top method, the printout is 'undefined', whereas using the second method, the printout is 'Peaches'.

This wouldn't affect me too much (since I could just always use the second method), however, when I try to export an array using the second method it prints out as undefined. But the confusing thing is that this only happens when I try to import two arrays (the second will always give 'undefined' yet the other will work. Is this to do with the flow of execution of the program? (So it has time to execute the first script, but not the second?

Vad Vad

Try this:

var peaches = 'Peaches';
exports.peaches = peaches;

In your first "method" you are not actually exporting anything.

The exports variable is just a plain JavaScript object created for each of your modules.