Node.Js Hello World Program
Overview
Node.js has become quite popular since its first release in 2009. Its usage on millions of websites and more than a billion downloads show that it stands firm in the Information technology world. Node.js offers asynchronous and event-driven architecture, efficiency, reusability, and scalability. Hence starting with Node.js is the preferred language for frontend and backend development. This article will introduce Node-specific concepts and build your way up to create a working program.
Introduction
Node.js is open-source software (publicly accessible), cross-platform (different operating environment) Javascript runtime environment that runs on the V8 JavaScript engine internally, which is the identical engine used to power the Google chrome browser JavaScript execution. The Node.js runtime is generally used to build web servers and command line tools.
As a result, Node.js allows developers to build server-side applications in Javascript as well as the front-end so that developers can build the entire stack project in the same language. Using the same language throughout your whole project can save time for libraries which can communicate more efficiently between your back-end server and front-end projects. Nodejs also reduce the time for context switching.
From a developer’s perspective, Node.js looks asynchronous, event-driven, and single-threaded, although, under the hood, Libuv handles threading and the Event loop. The V8 engines directly convert Javascript code to faster machine code which the interpreter can run more efficiently. Thus Node.js excels at I/O-intensive tasks, which is what makes Node. js so suitable for web application development. Real-time applications that continuously send and receive data, for example, video streaming or gaming, can run more efficiently when written in Node.js.
Download and Setup of Node.js
To write our first node js hello world program we need to install Node.js. This is the most important and basic prerequisite to writing your first Hello world program in Node.js. The way to install Node.js depends on what operating system you are using. Below is the most basic setup instruction to download and install Node.js in your system.
Installing Node.js on Windows System
By using the installer from the Node.js website.
The steps to install Node.js on Windows are as follows:
- Download the windows installer (.msi) file according to your system environment (64-bit or 32-bit). It contains a collection of essential files to install, update, or modify the Node.js versions on your system.
- Run the Node.js installer file. Double-click the (.msi) installer file. Click on the “Run” button on the first screen to begin the installation.
- Continue the installation steps. On the next screen, click the “Next” button to continue with the installation.
- Accept terms and conditions. Click on the “Next” button.
- Setup the directory path where you want Node.js files to be installed in your system. Click on the “Next” button to continue.
- Select the default components to be installed. Click the “Next” button.
- Start the installation. The installation will start and finish in a few minutes depending on your system. Click the “Finish” button to close the installation window.
- Verify the Node.js installation. Open the command prompt and type the following commands
The output will be the version of node installed. Similarly for npm do,
The output will be the version of npm installed.
Installing Node.js on MacOS System
By using the installer from the Node.js website.
Steps to install Node.js on MacOS to write your first node js hello world:
- Download the .pkg installer: Select Open with Installer and run it.
- Run the installer.
- Introduction window, On this screen click continue.
- Licence window, click agree and then press the continue button.
- Installation Type, click install and authenticate using your macOS username and password the continue installation.
- After successful completion a summary will be shown saying that Node.js and npm were installed.
- Close the installation wizard.
- Verify the Node.js installation. Open the command prompt and type the following commands
The output will be the version of node installed. Similarly for npm do,
The output will be the version of npm installed.
Installing Node.js on Linux System
By using Ubuntu's Official repository to install Node.js on Linux.
The steps to install Node.js on Ubuntu to write node js hello world are as follows:
- Refresh your local package index using
- Install Node.js using the following command
- Now install npm
- Verify the Node.js installation
Operating System | Directions |
---|---|
Mac OS | We can install Node.js on MacOS easily by using the installer from the official Node.js website. The alternative way to install Node.js is to use Homebrew and NVM (Node Version Manager). NVM also helps in the easy management of multiple active Node.js versions. |
Windows | We can install Node.js on Windows easily by using the installer from the official Node.js website. The alternative way to install Node.js is to use Chocolatey and nvm-windows(Node Version Manager). nvm-windows also helps in the easy management of multiple active Node.js versions |
Linux (Ubuntu) | There are various package managers available for each distribution. We can install Node.js by using the Ubuntu Official Repository. Alternatively, we can install Node.js in Linux using Node Source and personal package archive (PPA), it is recommended to use nvm to manage multiple active Node.js versions. |
Create Node js Hello World Application In Node.js Step By Step
Before diving into an actual Hello, World !!! application using Node.js, let us understand the elements of a Node.js application. There are three important components in a basic node js hello world program :
- Importing modules that are required for the program execution.
- Creating a server that will listen to client's requests (an HTTP server or creating a server using express)
- This server created in the 2nd step will receive and respond to the incoming HTTP requests.
Follow the given steps to make your node js hello world program:
Step 1: Open the command prompt on windows and type the given command to make a javascript file.
Step 2: Open the file in your favorite text editor. To open this file in VS code editor type the following command.
Step 3: Importing the required module for running your program. To make the basic Hello world program we only need an HTTP module for establishing the server. We need to load the module using the require keyword and store the returned HTTP instance into a variable as follows.
Step 4: Now you can create a server using the instance of the http module created above. We use the http.createServer() method to create a server, then bind it to port 8000 using the listen method associated with the http server instance. Now we pass that to a function with parameters request (req in short) and response (res in short) with a sample Hello, World !!!.
- Here the writeHead property of the 'http' module is used to send a response header to the request.
- The code in the above example is good enough to create an HTTP server locally on your machine which listens, i.e., waits for a request over port 8000.
- The console.log() object in Node.js provides a simple way to write to stderr, and stdout to any other Node.js stream, which in most cases is the command line. The log method prints to the stdout stream, so you can see it in your console.
Step 5: Now to run the above program, use the node command as follows:
Step 6: Verify the output in the console and on port 8000 of your local machine.
Also, open http://127.0.0.1:8000/ in any browser on your local machine and observe the following result.
Receiving User Input via Command Line Arguments :
In order to make the node js hello world program more dynamic apart from Hello, World; the user can take input from the command line and display the custom user input on the console. Users can provide various arguments via the command line. You can follow the following steps to take the dynamic arguments from the user.
Step 1: Create a main.js file on your system and open the same file in your choice of editor.
Step 2: Write the following code to display the custom argument taken from the user.
Step 3: Now run the program using the following syntax with a custom argument.
Step 4: Verify the output.
Explanation: Node.js provides us with the global object process that contains all the data and functions that are related o the current Node.js program. The argv is an array of strings that contains all the command line arguments given by a user.
The first two arguments in the process.argv array are reserved; that is, the first argument is the location of the Node.js binary which is running your program. The second argument is the file location of your program. The remaining are the custom arguments that the user entered, in this case: This, is, the, custom, argument . Also, the environment variable can be accessed using process.env.
Now after writing your first Hello world program in Nodejs to taking input from the user, all the basics are clear.
Accessing Environment Variables
Environment variables are used to store secret key-value data, which is provided by the operating system or user and is stored outside the program. They are set by the user and should be available to all the running processes for configuration or state purposes. You can use Node’s. In order to access environment variables in the node js hello world program we use the process object.
You can follow the following steps to check the current environment variable for a node js hello world or any other program.
Step 1: Create a main.js file on your system and open the same file in your choice of editor.
Step 2: Write the following code to display the environment object. The env object stores all the key-value environment variables that are available when Node.js is running the current program.
Step 3: Now run the program using the following syntax with custom argument.
Step 4: Check the output.
The environment variables in the above output are dependent on your system environment and configuration and may be different for different systems. You can access any specified environment variable using its key, such as process.env["HOME"] will only print the HOME property of process.env, which stores the value of the $HOME and not the entire object.
Node.js is changing the way we build web applications. Enroll in our Free Node JS certification course and become a part of this revolutionary shift in web development.
Conclusion
- Node.js is an open-source, cross-platform Javascript runtime environment that runs on chrome's V8 engine internally.
- For setting up the Node.js development environment: install Node.js, install a text editor and create a javascript file.
- Creating a node js hello world program just requires an HTTP module for server setup.
- Running the Node.js file can be done by following the command.
- We can take custom input from the user via command-line arguments
- Node.js provides us with the global object process that contains all the data and functions that are related o the current Node.js program.
- the first two arguments of process.argv are reserverd, first is Node.js binary location, and the second is the file location of a current running program.
- We can access the custom arguments in the Node.js program file using the process.argv method.
- We can access the environment variable of the system in the Node.js using process.env method.