NodeJs require('./file.js') issues

node.jsRequire

node.js Problem Overview


I am having issues including files to execute in my NodeJs project.

I have two files in the same directory:

a.js

var test = "Hello World";

and

b.js

require('./a.js');
console.log(test);

I execute b.js with node b.js and get the error ReferenceError: test is not defined.

I have looked through the docs http://nodejs.org/api/modules.html#modules_file_modules

What am I missing? Thanks in advance.

node.js Solutions


Solution 1 - node.js

Change a.js to export the variable:

exports.test = "Hello World";

and assign the return value of require('./a.js') to a variable:

var a = require('./a.js');
console.log(a.test);

Another pattern you will often see and probably use is to assign something (an object, function) to the module.exports object in a.js, like so:

module.exports = { big: "string" };

Solution 2 - node.js

You are misunderstanding what should be happening. The variables defined in your module are not shared. NodeJS scopes them.

You have to return it with module.exports.

a.js

module.exports = "Hello World";

b.js

var test = require('./a.js');
console.log(test);

Solution 3 - node.js

if you want to export the variable in another file.There are two patterns. One is a.js
global.test = "Hello World"; //test here is global variable,but it will be polluted

The other is
a.js module.exports.test = "Hello World"; or exports.test= "Hello World"; b.js var test = require('./a.js'); //test in b.js can get the test in a.js console.log(test);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrick LorioView Question on Stackoverflow
Solution 1 - node.jsrdreyView Answer on Stackoverflow
Solution 2 - node.jsAndrew T FinnellView Answer on Stackoverflow
Solution 3 - node.jsphilipzhaoView Answer on Stackoverflow