Lets begin with the hello world program.
Create a file called helloworld.js using your favorite Text Editor.
let hello = `Welcome to NodeJS Tutorial. Hello World!`console.log(“Welcome to NodeJS Tutorial”);
To run this code, open up a command shell/terminal and execute the following code.
node helloworld
The output will be a beautiful message starting at you on the screen.
The output will be this beautiful message staring at you on the screen.
How is the code in the node file executed?
In the Node.js module system, each file is treated as a separate module. So, in our case, the helloworld.js and global.js are separate modules.
The main source code/script is wrapped in an IIFE (Immediately Invoked Function Expression) which passes some global object to every module/file. To learn more about IIFE's, check out this tutorial: Advanced Functions: IIFEs, Closures, and the Module Pattern)
The code may look like below
(function(exports, require, module, __filename, __dirname) {// Module code actually lives in here// For e.g. our helloworld.js})(exports, require, module,__filename, __dirname);
You can see now, this is the reason why require , module, __filename, __dirname is directly available in all node.js files without specifically requiring or importing.