How to define const in nodejs in global scope?

I want to split my application into parts in order to have something like MVC ... Currently, I realized that exports works and how to communicate between different files. The only thing I can’t understand is how to use constants globally? I currently have something like this:

 // start.js const ROOT_DIR = __dirname; const APP_DIR = ROOT_DIR + '/app/'; const MODULES_DIR = '/usr/local/lib/node_modules/'; const APP_PORT = 4935; var server = require(APP_DIR + 'server.js'); server.start(); // server.js exports.start = function() { var express = require(MODULES_DIR + 'express'), app = express(), http = require('http'), server = http.createServer(app), io = require(MODULES_DIR + 'socket.io').listen(server), fs = require('fs'), path = require('path'); server.listen(APP_PORT); app.use(express.static(ROOT_DIR + '/assets')); app.get('/', function (req, res) { res.sendfile(ROOT_DIR + '/views/index.html'); }); } 

Is it possible to automatically set these constants to server.js or do I need to pass them as variables?

+6
source share
4 answers

I think you need to create a file with constants and use it as the required file at the beginning of another module.

File consts.js

 exports.CONST_1 = 42, exports.CONST_2 = 123; 

In the module, where necessary:

 var consts = require('path_to_consts.js'); var my_var = consts.CONST_1 + consts.CONST_2; 

So, all global variables will be in one place

+14
source

Object.defineProperty(global, 'MY_CONST', { value : 123 })

PS Please do not do this

+1
source

Javascript constants will not work globally through files in Node.js. You need to pass their functions.

  // start.js const ROOT_DIR = __dirname; const APP_DIR = ROOT_DIR + '/app/'; const MODULES_DIR = '/usr/local/lib/node_modules/'; const APP_PORT = 4935; var server = require(APP_DIR + 'server.js'); server.start(MODULES_DIR,APP_PORT,ROOT_DIR); // server.js exports.start = function(MODULES_DIR,APP_PORT,ROOT_DIR) { var express = require(MODULES_DIR + 'express'), app = express(), http = require('http'), server = http.createServer(app), io = require(MODULES_DIR + 'socket.io').listen(server), fs = require('fs'), path = require('path'); server.listen(APP_PORT); app.use(express.static(ROOT_DIR + '/assets')); app.get('/', function (req, res) { res.sendfile(ROOT_DIR + '/views/index.html'); }); } 
0
source

This method is similar to that suggested by @ user3040347, but is slightly different.

Here you need to create a file with constants and use it as the required file at the beginning of the module in which you want to use.

File consts.js

 CONST_1 = 42, CONST_2 = 123; module.exports = {}; 

In the module, where necessary:

 var consts = require('path_to_consts.js'); var my_var = CONST_1 + CONST_2; //Here you can access directly 
0
source

Source: https://habr.com/ru/post/958915/


All Articles