How do you share constants in NodeJS modules? - javascript

Currently I'm doing this:
foo.js
const FOO = 5;
module.exports = {
FOO: FOO
};
And using it in bar.js:
var foo = require('foo');
foo.FOO; // 5
Is there a better way to do this? It feels awkward to declare the constant in the exports object.

In my opinion, utilizing Object.freeze allows for a DRYer and more declarative style. My preferred pattern is:
./lib/constants.js
module.exports = Object.freeze({
MY_CONSTANT: 'some value',
ANOTHER_CONSTANT: 'another value'
});
./lib/some-module.js
var constants = require('./constants');
console.log(constants.MY_CONSTANT); // 'some value'
constants.MY_CONSTANT = 'some other value';
console.log(constants.MY_CONSTANT); // 'some value'

Technically, const is not part of the ECMAScript specification. Also, using the "CommonJS Module" pattern you've noted, you can change the value of that "constant" since it's now just an object property. (not sure if that'll cascade any changes to other scripts that require the same module, but it's possible)
To get a real constant that you can also share, check out Object.create, Object.defineProperty, and Object.defineProperties. If you set writable: false, then the value in your "constant" cannot be modified. :)
It's a little verbose, (but even that can be changed with a little JS) but you should only need to do it once for your module of constants. Using these methods, any attribute that you leave out defaults to false. (as opposed to defining properties via assignment, which defaults all the attributes to true)
So, hypothetically, you could just set value and enumerable, leaving out writable and configurable since they'll default to false, I've just included them for clarity.
Update - I've create a new module (node-constants) with helper functions for this very use-case.
constants.js -- Good
Object.defineProperty(exports, "PI", {
value: 3.14,
enumerable: true,
writable: false,
configurable: false
});
constants.js -- Better
function define(name, value) {
Object.defineProperty(exports, name, {
value: value,
enumerable: true
});
}
define("PI", 3.14);
script.js
var constants = require("./constants");
console.log(constants.PI); // 3.14
constants.PI = 5;
console.log(constants.PI); // still 3.14

ES6 way.
export in foo.js
const FOO = 'bar';
module.exports = {
FOO
}
import in bar.js
const {FOO} = require('foo');

You can explicitly export it to the global scope with global.FOO = 5. Then you simply need to require the file, and not even save your return value.
But really, you shouldn't do that. Keeping things properly encapsulated is a good thing. You have the right idea already, so keep doing what you're doing.

From previous project experience, this is a good way:
In the constants.js:
// constants.js
'use strict';
let constants = {
key1: "value1",
key2: "value2",
key3: {
subkey1: "subvalue1",
subkey2: "subvalue2"
}
};
module.exports =
Object.freeze(constants); // freeze prevents changes by users
In main.js (or app.js, etc.), use it as below:
// main.js
let constants = require('./constants');
console.log(constants.key1);
console.dir(constants.key3);

import and export (prob need something like babel as of 2018 to use import)
types.js
export const BLUE = 'BLUE'
export const RED = 'RED'
myApp.js
import * as types from './types.js'
const MyApp = () => {
let colour = types.RED
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.
If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).
But I guess this is the best we can get.
Additionally, here's a kind of improvement of Dominic's function, in constans.js:
global.define = function ( name, value, exportsObject )
{
if ( !exportsObject )
{
if ( exports.exportsObject )
exportsObject = exports.exportsObject;
else
exportsObject = exports;
}
Object.defineProperty( exportsObject, name, {
'value': value,
'enumerable': true,
'writable': false,
});
}
exports.exportObject = null;
In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).
First:
require( './constants.js' );
define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js
define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module
Second:
constants = require( './constants.js' );
// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js
Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:
exports.define = function ( name, value, exportsObject )
and use it like this in script.js:
constants.define( 'SOME_CONSTANT', "const value 1" );

I think that const solves the problem for most people looking for this anwwer. If you really need an immutable constant, look into the other answers.
To keep everything organized I save all constants on a folder and then require the whole folder.
src/main.js file
const constants = require("./consts_folder");
src/consts_folder/index.js
const deal = require("./deal.js")
const note = require("./note.js")
module.exports = {
deal,
note
}
Ps. here the deal and note will be first level on the main.js
src/consts_folder/note.js
exports.obj = {
type: "object",
description: "I'm a note object"
}
Ps. obj will be second level on the main.js
src/consts_folder/deal.js
exports.str = "I'm a deal string"
Ps. str will be second level on the main.js
Final result on main.js file:
console.log(constants.deal);
Ouput:
{ deal: { str: 'I\'m a deal string' },
console.log(constants.note);
Ouput:
note: { obj: { type: 'object', description: 'I\'m a note object' } }

As an alternative, you can group your "constant" values in a local object, and export a function that returns a shallow clone of this object.
var constants = { FOO: "foo" }
module.exports = function() {
return Object.assign({}, constants)
}
Then it doesn't matter if someone re-assigns FOO because it will only affect their local copy.

Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;.

I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.
'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');
module.exports = Object.freeze({
getDirectory: () => DIRECTORY,
getSheet: () => SHEET,
getComposer: () => COMPOSER
});

I recommend doing it with webpack (assumes you're using webpack).
Defining constants is as simple as setting the webpack config file:
var webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'APP_ENV': '"dev"',
'process.env': {
'NODE_ENV': '"development"'
}
})
],
};
This way you define them outside your source, and they will be available in all your files.

I don't think is a good practice to invade the GLOBAL space from modules, but in scenarios where could be strictly necessary to implement it:
Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});
It has to be considered the impact of this resource. Without proper naming of those constants, the risk of OVERWRITTING already defined global variables, is something real.

Related

Information flow in ES6 modules without using globals [duplicate]

I can't seem to find a description of the way I should export global variable from ES6 module. Is there a resource where it's defined?
The only solution that seems to work is referencing a global object, like window:
window['v'] = 3;
But what if this scripts runs in Node.js? Then I don't have window; I have global. But this code is not good:
var g = window || global;
g['v'] = 3;
I understand the concept of modules and don't use globals in my applications. However, having global variables during debugging in the console may be beneficial, especially when using bundlers like Webpack instead of loaders like SystemJs where you can easily import a module in a console.
There are several ways to have global values available in your application.
Using ES6 modules, you can create a constant which you export from your module. You can then import this from any other module or component, like so:
/* Constants.js */
export default {
VALUE_1: 123,
VALUE_2: "abc"
};
/* OtherModule.js */
import Constants from '../Constants';
console.log(Constants.VALUE_1);
console.log(Constants.VALUE_2);
Alternatively, some JS bundling tools provide a way to pass values into your components at build time.
For example, if you're using Webpack, you can use DefinePlugin to configure a few constants available at compile time, like so:
/* Webpack configuration */
const webpack = require('webpack');
/* Webpack plugins definition */
new webpack.DefinePlugin({
'VALUE_1': 123,
'VALUE_2': 'abc'
});
/* SomeComponent.js */
if (VALUE_1 === 123) {
// do something
}
You can grab the global object with an indirect eval call.
// this weird syntax grabs the global object
const global = (0,eval)("this");
// (0,eval) === eval; but the first one is an indirect evaluation
// inside indirect evaluation of eval, "this" is global object
// this takes advantage of that fact to identify "global"
// then set whatever global values you need
global.VALUE_1 = 123;
global.VALUE_2 = "abc";
You'll have to take care with the way your modules are loaded to ensure proper ordering.
more info: (1, eval)('this') vs eval('this') in JavaScript?
You can use globalThis:
function test(h) {
globalThis.testVar = h
}
test("This is a global var")
console.log(testVar)

What is the correct way to define global variable in ES6 modules?

I can't seem to find a description of the way I should export global variable from ES6 module. Is there a resource where it's defined?
The only solution that seems to work is referencing a global object, like window:
window['v'] = 3;
But what if this scripts runs in Node.js? Then I don't have window; I have global. But this code is not good:
var g = window || global;
g['v'] = 3;
I understand the concept of modules and don't use globals in my applications. However, having global variables during debugging in the console may be beneficial, especially when using bundlers like Webpack instead of loaders like SystemJs where you can easily import a module in a console.
There are several ways to have global values available in your application.
Using ES6 modules, you can create a constant which you export from your module. You can then import this from any other module or component, like so:
/* Constants.js */
export default {
VALUE_1: 123,
VALUE_2: "abc"
};
/* OtherModule.js */
import Constants from '../Constants';
console.log(Constants.VALUE_1);
console.log(Constants.VALUE_2);
Alternatively, some JS bundling tools provide a way to pass values into your components at build time.
For example, if you're using Webpack, you can use DefinePlugin to configure a few constants available at compile time, like so:
/* Webpack configuration */
const webpack = require('webpack');
/* Webpack plugins definition */
new webpack.DefinePlugin({
'VALUE_1': 123,
'VALUE_2': 'abc'
});
/* SomeComponent.js */
if (VALUE_1 === 123) {
// do something
}
You can grab the global object with an indirect eval call.
// this weird syntax grabs the global object
const global = (0,eval)("this");
// (0,eval) === eval; but the first one is an indirect evaluation
// inside indirect evaluation of eval, "this" is global object
// this takes advantage of that fact to identify "global"
// then set whatever global values you need
global.VALUE_1 = 123;
global.VALUE_2 = "abc";
You'll have to take care with the way your modules are loaded to ensure proper ordering.
more info: (1, eval)('this') vs eval('this') in JavaScript?
You can use globalThis:
function test(h) {
globalThis.testVar = h
}
test("This is a global var")
console.log(testVar)

How to properly export from required node file

I have been reading about Node's require and how its exports is automatically overridden when a module.exports has data or functionality declared within it. So let me see if I understand correctly: anything that I put in exports will be included in files which require the file.
I have inherited some node files, one main file with heaps of requires, and each required file with the structure:
var obj = {};
obj.prop1 = "some value1";
obj.prop2 = "some value2";
module.exports = exports = obj;
Is this a standard way of exporting data in a required file? Is it sensible to a)declare this (seemingly redundant obj)? ,b)if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj? c)what is the purpose of this middle-level exports if it can be overridden? What is the use case for both of these objects?
what is the purpose of this middle-level exports if it can be overridden?
exports is initially set to the value of module.exports and is available as a convenience (and default value), so that you don't have to create your own object to export values. Your example is basically equivalent to just using:
exports.prop1 = "some value1";
exports.prop2 = "some value2";
if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj
If you want to export obj from the module, you have to assign it to module.exports. That's how Node knows which value to return when the module is required.
The assignment to exports is not really necessary, but it can prevents mistake like
module.exports = {foo: 42};
// now `module.exports` and `exports` point to different objects
// the following export is just "lost" (ignored)
exports.bar = 21;
The assignments (module.exports = exports = ...) ensures that both, module.exports and exports point to the same object so mutations via either variable have an effect.
Is it sensible to declare this (seemingly redundant obj)
There multiple ways to achieve what you want. I showed one at the top using exports directly. You could also just write
module.exports = {
prop1: "some value1",
prop2: "some value2"
};
Use whatever makes sense to you and complies with the style guidelines you are following.
At the end of the day, the value you want to export must be assigned to module.exports. How you do that is up to you.

Expressjs JavaScript Fundamentals: exports = module.exports = createApplication;

I don't know what this pattern is called, if I did I would look it up directly.
Mainly, how does this work? (This code is taken from Express.js)
exports = module.exports = createApplication;
I have seen similar patterns before where there is this type of reference variable chain ex:
x = y = z
I understand exports vs module.exports but looking at the pattern above it makes me question on how it actually works.
I go by the general rule of thumb that 'module.exports' is the real deal, and 'exports' is its helper, more on this here
Is the module pattern like this (without altering module.exports)?
exports = module.exports = {};
ex:
exports.name = 'hello'
results to
exports = module.exports = {name: 'hello'}
What happens when you change the reference on exports?
exports = {name: 'bob'}
Now when you add to exports, it will reference the `{name: 'bob'} and no longer have any ties with module.exports?
Your intuition is correct. I'll work from the bottom up:
The Node.js Wrapper
Before running any file, Node.js wraps the entire script in an immediately-invoked function expression (IIFE):
(function (exports, require, module, __filename, __dirname) {
// ...script goes here...
});
This is how it introduces the module and exports variables into the scope; they're nothing more special than function arguments.
Using exports
The Node.js docs on module.exports and the exports alias are pretty helpful. To start out, module.exports and the exports variable both refer to the same empty object that was created by the module system.
If a module simply needs to export a plain old JavaScript object with some properties set, exports is all that's needed:
exports.get = function(key) {
// ...
};
exports.set = function(key, value) {
// ...
};
When code require()s this module, the result will look something like:
{
get: [Function],
set: [Function]
}
Replacing module.exports
However, Express exports a constructor function, createApplication, as the root value. To export the function itself, rather than just assigning it to a property on the exported object, it must first replace the exported object entirely:
module.exports = createApplication;
Now, exports hasn't been updated and still refers to the old object, whereas module.exports is a reference to createApplication. But if you keep reading, you'll notice that Express exports several other properties in addition to the constructor. While it would be sufficient to assign these to properties on the new value of module.exports, it is shorter to reassign exports so that it is again an alias to module.exports, then assign those properties on exports, which is equivalent to assigning them on module.exports.
Thus, these examples are functionally equivalent:
module.exports = createApplication;
function createApplication() {
// ...
}
module.exports.application = proto;
module.exports.request = req;
module.exports.response = res;
But this one is less verbose:
exports = module.exports = createApplication;
function createApplication() {
// ...
}
exports.application = proto;
exports.request = req;
exports.response = res;
Either way, the result is the same, a function named createApplication at the root with properties available on it:
{
[Function: createApplication]
application: [Object],
request: [Object],
response: [Object],
// ...a few other properties...
}

What do "module.exports" and "exports.methods" mean in NodeJS / Express?

Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
and
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
I understand that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don't understand exactly how it works, or what the code in the line means.
What do exports and module.exports actually mean?
I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.
Basically, what are these magic words: module and exports?
To be more specific:
module is the global scope variable inside a file.
So if you call require("foo") then :
// foo.js
console.log(this === module); // true
It acts in the same way that window acts in the browser.
There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL
exports is a variable that lives on module.exports. It's basically what you export when a file is required.
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
Read more about exports
To expand on Raynos's answer...
exports is basically an alias for module.exports - I recommend just not using it. You can expose methods and properties from a module by setting them on module.exports, as follows:
//file 'module1.js'
module.exports.foo = function () { return 'bar' }
module.exports.baz = 5
Then you get access to it in your code:
var module1 = require('module1')
console.log(module1.foo())
console.log(module1.baz)
You can also override module.exports entirely to simply provide a single object upon require:
//glorp.js
module.exports = function () {
this.foo = function () { return 'bar' }
this.baz = 5
return this // need to return `this` object here
}
Now you've got a nice prototype:
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
There are myriad other ways to play with module.exports and require. Just remember, require('foo') always returns the same instance even if you call it multiple times.
Note
For the following to work,
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
this has to be returned in the function that is assigned to module.exports. Otherwise, you'll get a TypeError:
console.log(g1.foo())
^
TypeError: Cannot read property 'foo' of undefined
You can find the best answer in node.js source code.
If someone is requiring your js module,
your script turns into a function by node as follows (see src/node.js).
// require function does this..
(function (exports, require, module, __filename, __dirname) {
... your javascript contents...
});
Node will wrap your script. Then above script will be executed as follows:
//module.js
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);
So in your script,
exports is just module.exports.
In your script, you can add something to this exports object (functions..).
require function will return this object. This is node.js's module system (commonJS specification).
But be careful not to modify module.exports. Otherwise your current exports will be meaningless.
module is an object that represents what that particular source file would like to publicly expose. Instead of having something akin to header files in the c/c++ world, you describe what the module exports by defining this object. the node runtime then uses this object to determine what about your module is 'public.'
its a similar concept to exporting functions from a dll in the compiled world. you have to define explicitly what functions can be accessed by the outside world. this helps with encapsulation and lets your organize your libraries in a clean way.
Module's code is wrapped in module.exports (The module, maybe composed by other module).
There are many ways to build a module, but this is one very common (and my personal favorite).
// Dependencies
// const module = require('module');
// Module object
var foo = {}
// Internal property
foo._a = 'a';
// "Public" property
foo.b = 'b';
// Method
foo.fu = function() { return 'fu' };
// Export
module.exports = foo;

Categories