The documentation says there are some core modules that are shipped as part of the platform and are defined within the Node.js source. Looking after details, the nomenclature becomes a bit convoluted. "The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, 'global objects' refer to objects in the global scope."
As I understand, there is a global object that is accessible by explicitly writing 'global', as in:
console.log(global)
It contains some things that you want to be accessed across all your files, like the console or the process object. There are other things that may appear global, but are not, they are there because all Node.js scripts are implicitly wrapped in the following:
(function (exports, require, module, __filename, __dirname) {
// Userland code comes here
});
There are other objects that come as the 'implementation' of the Javascript language itself, like Object, Function, or Boolean.
What I don't understand, but still seems important though, is the following. Why is it then that there are some things shipped with Node.js that are available without any third-party libraries, but you still have to require them (like the 'events', or 'fs' module)? It seems to me that the whole reason of having a global object that is accessible to all files is that the core things that you might use can be exposed there.
I know that my question might be opinion-based, but is this just another implementation detail, or is there something that I do not get conceptually and should be considered in day-to-day development?
The documentation says there are some core modules that are shipped as part of the platform and are defined within the Node.js source.
All core modules are shipped with Node.js. That's the definition of "core."
The vast majority of them aren't loaded into memory by default, and aren't assigned a global identifier by default. To use them, you have to load them (via require
or, in modern environments, import
.) That's a good thing. There's no good reason to load the fs
module if no code being run is going to need it, and there's really no good reason to create a global fs
identifier — the global namespace is already overcrowded.