Home >Web Front-end >JS Tutorial >How to Get Started with NodeJS – a Handbook for Beginners
Node is an environment in which you can run JavaScript code "Outside the web browser". Node be like – "Hey y'all, you give your JS code to me and I'll run it 😎". It uses Google's V8 Engine to convert the JavaScript code to Machine Code.
Since Node runs JavaScript code outside the web browser, this means that it doesn't have access to certain features that are only available in the browser, like the DOM or the window object or even the localStorage.
This means that at any point in your code, you can't type in document.querySelector() or alert() as these will produce errors (This is what is shown in the below image).
Remember: Node is meant for server-side programming, while those browser features are meant for client-side programming.
Front-end folks don't be sad – there's more to it! Node provides you with lots of API's and Modules with which you can perform a variety of operations like File Handling, Creating Servers, and much more. Before diving into the NodeJS, first let's install it in our machine.
Installing NodeJS is straightforward. If you already have Node installed in your machine, you can skip this section. If not, then follow along.
Here are the steps to download NodeJS on your machine:
Note: If you encounter any issues during the installation process, you can refer to the official NodeJS documentation for more detailed instructions and troubleshooting tips.
Let's start this article by learning about some variables present in NodeJS called Global Variables. These are basically variables which store some data and can be accessed from anywhere in your code – doesn't matter how deeply nested the code is.
You should know about these commonly used Global variables:
Let's use them and see what value they contain. For this, let's create a new folder called NodeJSTut in your Desktop and open it up with your favorite text editor (In the entire tutorial, we will be using VS Code). Create a new file called app.js and open up a new integrated VS Code Terminal.
Paste the following code in the app.js file and save it:
// __dirname Global Variableconsole.log(__dirname);// __filename Global Variableconsole.log(__filename);
To run this code using Node, type in the following command in the terminal and press Enter: node app.js. You will see the absolute path to the present working directory and the path to the current file is printed in the terminal. This is what the output looks like in my case:
C:\Desktop\NodeJSTut C:\Desktop\NodeJSTut\app.js
You can go ahead and create your own global variables which can be accessed from anywhere in your code. You can do so, like this:
// Define a global variable in NodeJSglobal.myVariable = 'Hello World';// Access the global variableconsole.log(myVariable); // Output: Hello World
In Node.js, a module is essentially a reusable block of code that can be used to perform a specific set of tasks or provide a specific functionality. A module can contain variables, functions, classes, objects, or any other code that can be used to accomplish a particular task or set of tasks.
The primary purpose of using modules in Node.js is to help organize code into smaller, more manageable pieces. A modules can then be imported at any time and used flexibly which helps in creating reusable code components that can be shared across multiple projects.
To understand this, consider this example: Let's say you have defined lots of functions in your code that works with a huge volume of JSON data.
Losing your sleep and increased anxiety levels are common side effects of keeping all this stuff (functions data some other logic) in one single file.
So you, being a clever programmer, thought of making a separate file for the JSON data and a separate file for storing all the functions. Now, you can simply import the data and the functions whenever you want and use them accordingly. This method increases efficiency as your file size reduces drastically. This is the concept of modules!
Let's see how we can make our own modules. For this, we are going to write some code where we will be defining a function called sayHello() in a file called hello.js. This function will accept a name as the parameter and simply print a greeting message in the console.
We will then import it in another file called app.js and use it there. How interesting, right 😂? Let's check out the code:
This is the code in hello.js file:
function sayHello(name){ console.log(`Hello ${name}`);}module.exports = sayHello
This is the code in app.js file:
const sayHello = require('./hello.js');sayHello('John');sayHello('Peter');sayHello('Rohit');
The file hello.js can be called the module in this case. Every module has an object called exports which should contain all the stuff you want to export from this module like variables or functions. In our case, we are defining a function in the hello.js file and directly exporting it.
The app.js file imports the sayHello() function from hello.js and stores it in the sayHello variable. To import something from a module, we use the require() method which accepts the path to the module. Now we can simply invoke the variable and pass a name as a parameter. Running the code in app.js file will produce the following output:
Hello John Hello Peter Hello Rohit
In the previous section of the article, we saw how to use module.exports but I felt that it is important to understand how it works in a bit more detail. Hence, this section of the article is like a mini tutorial where we will see how we can export one variable/function as well as multiple variables and functions using module.exports. So, Let's get started:
module.exports is a special object in NodeJS that allows you to export functions, objects, or values from a module, so that other modules can access and use them. Here's an example of how to use module.exports to export a function from a module:
// myModule.jsfunction myFunction() { console.log('Hello from myFunction!');}module.exports = myFunction;
In this example, we define a function myFunction and then export it using module.exports. Other modules can now require this module and use the exported function:
// app.jsconst myFunction = require('./myModule');myFunction(); // logs 'Hello from myFunction!'
Everything seems fine now and life is good. But the problem arises when we have to export multiple functions and variables from a single file. The point is when you use module.exports multiple times in a single module, it will replace the previously assigned value with the new one. Consider this code:
// module.jsfunction myFunction() { console.log('Hello from myFunction!');}function myFunction2() { console.log('Hello from myFunction2!');}// First Exportmodule.exports = myFunction;// Second Exportmodule.exports = myFunction2;
In this example, we first export myFunction(). But we then overwrite module.exports with a new function - myFunction2(). As a result, only the second export statement will take effect, and the myFunction() function will not be exported.
This problem can be solved if you assign module.exports to an object which contains all the functions you want to export, like this:
// myModule.jsfunction myFunction1() { console.log('Hello from myFunction1!');}function myFunction2() { console.log('Hello from myFunction2!');}module.exports = { foo: 'bar', myFunction1: myFunction1, myFunction2: myFunction2};
In this example, we export an object with three properties: foo, myFunction1, and myFunction2. Other modules can require this module and access these properties:
// app.jsconst myModule = require('./myModule');console.log(myModule.foo); // logs 'bar'myModule.myFunction1(); // logs 'Hello from myFunction1!'myModule.myFunction2(); // logs 'Hello from myFunction2!'
To summarize, you can use module.exports as many times as you want in your NodeJS code, but you should be aware that each new assignment will replace the previous one. You should use an object to group multiple exports together.
There are 2 types of modules in NodeJS:
Here is an image of popular built-in modules in NodeJS and what can you do using them:
Let's go over each of these in more detail so you can learn more about what they do.
The OS Module (as its name implies) provides you methods/functions with which you can get information about your Operating System.
To use this module, the first step is to import it like this:
const os = require('os');
This is how you can use the OS Module to get information about the Operating System:👇
const os = require('os')// os.uptime()const systemUptime = os.uptime();// os.userInfo()const userInfo = os.userInfo();// We will store some other information about my WindowsOS in this object:const otherInfo = { name: os.type(), release: os.release(), totalMem: os.totalmem(), freeMem: os.freemem(),}// Let's Check The Results:console.log(systemUptime);console.log(userInfo);console.log(otherInfo);
This is the output of the above code:
Note that the output shows information about the Windows Operating System running on my system. The output could be different from yours.
521105 { uid: -1, gid: -1, username: 'krish', homedir: 'C:\\Users\\krish', shell: null } { name: 'Windows_NT', release: '10.0.22621', totalMem: 8215212032, freeMem: 1082208256 }
Let's break down the above code and output:
{ uid: -1, gid: -1, username: 'krish', homedir: 'C:\\Users\\krish', shell: null }
The uid and gid is set to -1 in Windows, because Windows does not have the concept of user IDs like Unix-based systems. The username of my OS is krish and the home directory is 'C:\\Users\\krish'. The shell is set to null because the concept of a default shell does not exist on Windows. Windows has a default command interpreter program called Command Prompt (cmd.exe), which runs commands and manages the system.
The other methods related to OS Module like os.type(), os.release() and so on, which you saw in the above code has been used within the otherInfo object. Here is a breakdown of what these methods do:
This is the information which the above methods display about my OS:
{ name: 'WindowsNT', // Name of my OS release: '10.0.22621', // Release Version of my OS totalMem: 8215212032, // Total Memory Available in bytes (~ 8 GB) freeMem: 1082208256 // Free Memory Available in bytes (~ 1 GB) }
The PATH module comes in handy while working with file and directory paths. It provides you with various methods with which you can:
You an see the PATH Module in action in the code below.
Code:
// Import 'path' module using the 'require()' method:const path = require('path')// Assigning a path to the myPath variableconst myPath = '/mnt/c/Desktop/NodeJSTut/app.js'const pathInfo = { fileName: path.basename(myPath), folderName: path.dirname(myPath), fileExtension: path.extname(myPath), absoluteOrNot: path.isAbsolute(myPath), detailInfo: path.parse(myPath),}// Let's See The Results:console.log(pathInfo);
Output:
{ fileName: 'app.js', folderName: '/mnt/c/Desktop/NodeJSTut', fileExtension: '.js', absoluteOrNot: true, detailInfo: { root: '/', dir: '/mnt/c/Desktop/NodeJSTut', base: 'app.js', ext: '.js', name: 'app' } }
Let's have a detailed breakdown of the above code and its output:
The first and foremost step to work with path module is to import it in the app.js file using the require() method.
Next, we are assigning a path of some file to a variable called myPath. This can be a path to any random file. For the purpose of understanding the path module, I chose this: /mnt/c/Desktop/NodeJSTut/app.js.
Using the myPath variable, we will understand the path module in detail. Let's check out the functions which this module has to offer and what can we do with it:
However, if you just change the myPath variable to this: Desktop/NodeJSTut/app.js (converting it to a relative path), isAbsolute() returns false.
Before continuing with the other functions of the path module, we need to understand something called path separator and the path structure.
You must have seen that the path to a same file looks different in different Operating Systems. For example, consider the path to a file named example.txt located in a folder called Documents on the desktop of a Windows user:
C:\Users\username\Desktop\Documents\example.txt
On the other hand, the file path to the same file for a user on a macOS system would look like this:
/Users/username/Desktop/Documents/example.txt
2 differences are to be noted here:
With this in mind, let's move ahead and understand some other functions provided by the path module:
console.log(path.join('grandParentFolder', 'parentFolder', 'child.txt'))
The above code prints different results for different Operating Systems.
In Windows, it will give this output: grandParentFolder\parentFolder\child.txt while in macOS/Linux, it will give this output: grandParentFolder/parentFolder/child.txt. Note that the difference is only in the path separators - backward slash and forward slash.
Suppose you are a Windows user and the absolute path to your present working directory is this: C:\Desktop\NodeJSTut, If you run this code:
console.log(path.resolve('grandParentFolder', 'parentFolder', 'child.txt'));
You will see the following output in the console:
C:\Desktop\NodeJSTut\grandParentFolder\parentFolder\child.txt
The same is applicable to a macOS or a Linux user. It's just the difference in the absolute path of the present working directory and the path separator.
The above is the detailed content of How to Get Started with NodeJS – a Handbook for Beginners. For more information, please follow other related articles on the PHP Chinese website!