简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM