Hello World App In Node.js

NodeJS

NodeJS is a lean, fast, cross-platform Javascript runtime environment that is useful for both servers and desktop applications. In this article, I am assuming that you have installed Node.js on your PC. If you have not installed it go to this link and install it https://nodejs.org/en/ 

Visual Studio Code

Visual Studio Code is a very nice editor for a NodsJS app. I really love it and I also recommend this to you as well. But this is not necessary, you can use anyone else according to your interest and with which you are comfortable. It's just my suggestion.

Ok... Let me show you an overview of Visual Studio.

Node.js

This is the first window of the Visual Studio Code. In the left corner, there is a window opened which is Explorer. Your files and folders will be here and you can easily access them. Create a folder and open it in Visual Studio Code. In my case, I have a folder HelloWorld.

Now, open Terminal/Console in Visual Studio Code. You can go to View>Integerated Terminal and open it. You can open it with a shortcut as well as its shortcut is Ctrl+.

When you open terminal type npm init as below,

npm init

This will create a package.json file in your folder. Actually, this file has references for all npm packages you have downloaded to your project. When you install a new npm package it references will be added in this file.

Create a new file in your folder and name it app.js. Then type the following command in your terminal,

npm install express --save

This will install the express framework for your project. It has a lot of files, dependencies, and modules as following,

Node.js

You can see here it installed all the packages that we need for our project.

Open your app.js file and add following code,
  1. var express = require('express');  
  2. var app = express();  
  3. app.get('/'function(req, res) {  
  4.     res.send('Hello World');  
  5. });  
  6. app.listen(3000, function() {  
  7.     console.log('Example app listening on port 3000!');  
  8. });  
This will add an express module in app.js. And the function in lines 4 to 6 will be called when the application runs. The function from line 8 to 10 tells us that the application will run on port 3000 and will display a message in console.log.

Then run the following command in your terminal to run your app.

node app.js

The application will run, open your localhost with port 3000. It will show the following,

Node.js
You see in the browser it is showing Hello World that I wrote in the app.js file.


Similar Articles