Pumych
Pumych

Reputation: 1398

node.js express - require file in all files

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" :(

Upvotes: 0

Views: 542

Answers (1)

Carl K
Carl K

Reputation: 984

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';

Upvotes: 1

Related Questions