How to share constants in Node.js modules?

Sometimes, we want to share constants in Node.js modules.

In this article, we’ll look at how to share constants in Node.js modules.

How to share constants in Node.js modules?

To share constants in Node.js modules, we can put them all in a module and export them.

For instance, we write

./constants.js

module.exports = Object.freeze({
  MY_CONSTANT: 'some value',
  ANOTHER_CONSTANT: 'another value'
});

to set module.exports to a frozen object with some properties inside with the constant values.

We freeze the object with Object.freeze so it can’t be modified accidentally.

Then we can import the constants with

./app.js

const constants = require('./constants');

console.log(constants.MY_CONSTANT);
console.log(constants.ANOTHER_CONSTANT);

We call require with the path to ./constants.js.

Then we get the values from constants.

Conclusion

To share constants in Node.js modules, we can put them all in a module and export them.