Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
Petter Thowsen Avatar asked Sep 24 '13 13:09

Petter Thowsen


1 Answers

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
like image 62
hexacyanide Avatar answered Oct 10 '22 02:10

hexacyanide