Share constants in NodeJS modules

This article will show how you can share constants in NodeJS modules.

Sharing constants in Node.js modules is a common requirement in projects to maintain a clean and organized codebase. There are various approaches suggested by the community, and in this tutorial, we’ll explore different methods to share constants while emphasizing best practices.

Using Object.freeze

The Object.freeze method is a simple and effective way to create constants in Node.js. This method prevents modifications to the object, making it immutable. Follow these steps:

./lib/constants.js

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

Explanation:

  • In this method, a module is created in the constants.js file using Object.freeze.
  • Object.freeze is a method in JavaScript that prevents the modification of an object. It makes the object immutable.
  • The module exports an object containing key-value pairs, representing the constants.
  • By using Object.freeze, any attempt to modify the constants after their declaration will have no effect.

./lib/some-module.js

// some-module.js
var constants = require('./constants');

console.log(constants.MY_CONSTANT); // 'some value'

// Attempting to modify will have no effect
constants.MY_CONSTANT = 'some other value';

console.log(constants.MY_CONSTANT); // 'some value'

Explanation:

  • In some-module.js, the constants module is imported using require.
  • The constants are accessed and used in the application.
  • An attempt to modify a constant value (constants.MY_CONSTANT) is demonstrated, and it shows that the value remains unchanged due to the use of Object.freeze.

This method provides a simple and effective way to create constants with immutability.

Using Object.defineProperty

If you want to enforce true constants and prevent any modifications, you can use Object.defineProperty. This method provides more control over the properties of the object.

./lib/constants.js

// constants.js
function define(name, value) {
    Object.defineProperty(exports, name, {
        value: value,
        enumerable: true,
        writable: false,
        configurable: false
    });
}

define("PI", 3.14);

Explanation:

  • This method uses Object.defineProperty to create constants with more control over their properties.
  • The define function is created to encapsulate the definition process. It uses Object.defineProperty to set properties like value, enumerable, writable, and configurable.
  • In this example, a constant PI is defined with a value of 3.14, and it’s made non-writable and non-configurable.

./lib/script.js

// script.js
var constants = require("./constants");

console.log(constants.PI); // 3.14

// Attempting to modify will have no effect
constants.PI = 5;

console.log(constants.PI); // still 3.14

Explanation:

  • In script.js, the constants module is imported, and the PI constant is accessed and used.
  • An attempt to modify the value of PI is demonstrated, and it shows that the value remains unchanged due to the non-writable property set during definition.

This method ensures that constants are truly read-only.

Using ES6 export and import

For a more modern approach, using ES6 syntax with export and import is an excellent choice.

./types.js

// types.js
export const BLUE = 'BLUE';
export const RED = 'RED';

Explanation:

  • This method utilizes ES6 export to define and export constants from a module.
  • Constants BLUE and RED are exported from the types.js module.
  • ES6 export allows for a cleaner and more modern syntax for module exports.

./myApp.js

// myApp.js
import * as types from './types.js';

const MyApp = () => {
    let colour = types.RED;
}

Explanation:

  • In myApp.js, constants are imported using ES6 import.
  • The import * as types syntax imports all exports from the types.js module into the types object.
  • Constants like RED can be accessed using the types object.

This method leverages modern ES6 syntax for cleaner and more readable code.

Global Scope (Not Recommended)

While it’s possible to export constants to the global scope, it’s generally not recommended due to potential issues with encapsulation.

However, if you still want to proceed.

./constants.js

// constants.js
'use strict';

let constants = {
    key1: "value1",
    key2: "value2",
    key3: {
        subkey1: "subvalue1",
        subkey2: "subvalue2"
    }
};

global.constants = Object.freeze(constants);

Explanation:

  • This method exports constants to the global scope, making them accessible throughout the application.
  • The global.constants object is assigned the value of the constants object, and Object.freeze is used to make it immutable.
  • Exporting constants globally is generally discouraged to maintain proper encapsulation.

Each method offers a different approach to sharing constants in Node.js, and the choice depends on project requirements and coding preferences. It’s essential to consider factors like immutability, readability, and maintainability when selecting a method.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top