It turns out that it became a common practice to use const
over var
for dependencies. At least in the Node.js source code this is happening:
So, I guess it's a good practice. I started to use it as well in my modules.
Frage
In NodeJS world we require modules using require
function:
var foo = require ("foo");
In JavaScript (also in NodeJS) we have const
keyword that creates a constant:
const
Creates a constant that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables.
Example:
$ node
> const a = 10
undefined
> a
10
> a = 7
7
> a
10
My question is: would it be good to require libraries as constans?
Example:
const foo = require ("foo")
, http = require ("http")
;
/* do something with foo and http */
Are there any bad/good effects using const
instead of var
when requiring libraries?
Lösung
It turns out that it became a common practice to use const
over var
for dependencies. At least in the Node.js source code this is happening:
So, I guess it's a good practice. I started to use it as well in my modules.
Andere Tipps
NodeJS hasn't any optimisations for library that requires as const - require
is a simple non native function, which nothing is known about the type of the variable to which is assigned. There is source code of require
:
Module.prototype.require = function(path) {
assert(util.isString(path), 'path must be a string');
assert(path, 'missing path');
return Module._load(path, this);
};
Module._load = function(request, parent, isMain) {
if (parent) {
debug('Module._load REQUEST ' + (request) + ' parent: ' + parent.id);
}
var filename = Module._resolveFilename(request, parent);
var cachedModule = Module._cache[filename];
if (cachedModule) {
return cachedModule.exports;
}
if (NativeModule.exists(filename)) {
// REPL is a special case, because it needs the real require.
if (filename == 'repl') {
var replModule = new Module('repl');
replModule._compile(NativeModule.getSource('repl'), 'repl.js');
NativeModule._cache.repl = replModule;
return replModule.exports;
}
debug('load native module ' + request);
return NativeModule.require(filename);
}
var module = new Module(filename, parent);
if (isMain) {
process.mainModule = module;
module.id = '.';
}
Module._cache[filename] = module;
var hadException = true;
try {
module.load(filename);
hadException = false;
} finally {
if (hadException) {
delete Module._cache[filename];
}
}
return module.exports;
};
For more time library is an object (I think you don't have library like this module.exports = 10
).
You can change all fields of object also if it is declared as const (If you want to get realy const object use Object.freeze(someObject)
).
For conclusion: the effect is the same as for a common variable. Link to V8 Variable Declaration Function used in NodeJS