Petter Thowsen
Petter Thowsen

Reputation: 1727

Is there a Node.js equivalent to PHP's include, so that included code has access to the parent file's variables?

I'd like to split my Node app into several separate files to make it more modular and easier to maintain.

But since there is no way to 'include' a file directly into the currently parsed file like in other languages like PHP, my 'modules' or 'separate files' do not automatically get access to the variables defined in the script that 'requires' them.

How can I do this?

I was thinking about doing something like this in my separate files:

module.exports = function(stuff) {
  //I now have access to 'stuff'.
}

But it's slightly cumbersome.

I'm sure someone has already tackled this before me so... what do you suggest?

Upvotes: 6

Views: 2414

Answers (1)

hexacyanide
hexacyanide

Reputation: 91769

The easiest way to share variables across modules is to assign the variables to the global namespace object. Variables declared how they would be globally declared in a browser are still module-specific in Node, so there is a global object.

Using the global scope is considered bad practice, but can be much simpler than other approaches:

foo.js

global.num = 3;
global.str = 'a string';
require('./bar');

bar.js

console.log(num);  // 3
console.log(str);  // a string

Upvotes: 2

Related Questions