1

Let's say I have too files, library, and main

content of library:

exports.someVariable = 5;

content of main:

var library = require('path/to/library')
print(library.someVariable) // correctly prints 5

But let's say I want to also use someVariable in library, maybe something like this:

content of library:

exports.someVariable = 5;
exports.someOtherVariable = someVariable+3; //will say it doesn't exist in this scope

What I tried content of library:

var someVariable = 5;
var someOtherVariable = someVariable+3; //it works so far
exports.someVariable;
exports.someOtherVariable;

content of main:

var library = require('path/to/library')
print(library.someVariable) // undefined
print(library.someOtherVariable) // undefined

Any suggestions?

1 Answer 1

2

This is the first time I'm answering my own question, and I always thought it's odd to answer your own question. Why ask if you know the answer, are people just bragging, but I digress, I figured out the answer while asking the question, so asking was very useful.

What I was missing is that exports.someVariable is a public separate variable that will be then available in main. The variable is obviously undefined until I put something in it, but I can't use it in lib (at least not in an obvious way). The way to go is to do your thing with regular variables (declared with var) and then at the end expose whatever variables you want to be public (accessible from main). Something like this:

content of library:

var someVariable = 5;
var someOtherVariable = someVariable+3; //it works so far
exports.someVariable = someVariable; they don't even need to be called the same, but probably that's what you want
exports.someOtherVariable = someOtherVariable;

content of main:

var library = require('path/to/library')
print(library.someVariable) // 5
print(library.someOtherVariable) // 8
library.someVariable = library.someOtherVariable + 2
print(library.someVariable) // 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.