0

Let say I need to do

require('./config/globals.js');

in many files, what is the best way to do it? Writing this line in every file or there is some more elegant way?

Searching "node.js how to require in many files" returns answers to "node.js require all files in a folder" :(

Pumych
  • 1,368
  • 3
  • 18
  • 31
  • possible duplicate of [Global Variable in app.js accessible in routes?](http://stackoverflow.com/questions/9765215/global-variable-in-app-js-accessible-in-routes) – Jerska Jul 04 '15 at 16:49
  • You can add a property to the "res" object to store the reference to your globals: res.globals = require(...) – Viktor Kireev Jul 04 '15 at 16:51

1 Answers1

1

If you have some global variables for your application that consists of multiple files and you want them to be accessible via all of the files in your application, define them as global variables in your main .js file:

server.js

global.myName = 'Carl';
require('app1.js');
require('app2.js');

In that scenario, both app1.js and app2.js will be able to read and write to the variabme myName.

Change the variables defined in your globals.js to follow the structure above, and it should achieve your goals - assuming I understood the question correctly.

EDIT: As seanhodges suggested, you could also keep the globals.js and edit accordingly:

Server.js

require('globals.js)
require('app1.js');
require('app2.js');

globals.js

global.myName = 'Carl';

Carl K
  • 974
  • 7
  • 18
  • The globals could even reside in the `./config/globals.js` file as long as it is `require`'d in the main .js file. – seanhodges Jul 04 '15 at 18:05