Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 690
Patrick Lorio Avatar asked Jul 30 '12 17:07

Patrick Lorio


People also ask

Why require is not working in js?

This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS.

Can I use require in js file?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do you fix require is not defined in NodeJS?

To fix this, remove "type": "module" from your package. json and make sure you don't have any files ending with . mjs . This can happen with anything in your project folder.

How do I use require in NodeJS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).


2 Answers

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" }; 
like image 151
rdrey Avatar answered Oct 07 '22 18:10

rdrey


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); 
like image 37
Andrew T Finnell Avatar answered Oct 07 '22 18:10

Andrew T Finnell