Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining public Constants file in node.js

Tags:

node.js

I am trying to create a single file to contain all Constants.

Here is my constants.js module:

module.exports.TRIP_STATUS = Object.freeze({   
  TRIP_STAUTS_INITIATED         : 1000,
  TRIP_STAUTS_PENDING_PRE_INSP  : 1001,
  TRIP_STAUTS_ACTIVE            : 1002,
  TRIP_STAUTS_PENDING_POST_INSP : 1003,
  TRIP_STAUTS_DONE              : 1004,
  TRIP_STAUTS_UNKNOWN           : 1005
});

In my main index.js i am trying to do something like

var Constants = require('constants');
console.log(Constants.TRIP_STAUTS_INITIATED);

However its not reading the enum.

What is wrong my code?

like image 773
Muhammad Umar Avatar asked Jun 24 '16 13:06

Muhammad Umar


People also ask

How do you declare a constant file in node?

You can use the define() method in other modules this manner, and it allows you to define constants both within the constants. js module and within the module from which the function was called.

Where do you put constants files?

All you have to do is take each section of your constants that are currently within index. js and put them within own their brand new file in /src/constants and link them to our constants/index.

How do I declare a global variable in node js?

To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.


1 Answers

You write constants object into TRIP_STATUS object. So, you can get them with the next way:

console.log(Constants.TRIP_STATUS.TRIP_STAUTS_INITIATED);

Or, you can do with the next way:

module.exports = {
    TRIP_STAUTS_INITIATED         : 1000,
    ...
}

And get constants as you want:

console.log(Constants.TRIP_STAUTS_INITIATED);
like image 66
Sergiy Avatar answered Oct 22 '22 19:10

Sergiy