Learn Simple Node Js with examples

Souvik Brahma
3 min readAug 17, 2018

--

Hello there, welcome to this blog, here we will go through a basic Node Js app, and learn about the same.

Lets start with creating a folder ‘ SimpleNodeApp ’ in Project directory.

Enter into SimpleNodeApp and open CMD / Terminal(For Linux users) with SimpleNodeApp as local directory.

This command line is where you will run your app from.

Now, lets initialize the project. Enter the following commands in command line.

npm init

Note : After executing this command you will be asked for various information, like package-name: , version: etc. You can simply press enter and move forward. Later on while practicing you will get these stuffs.

This command will initialize the app by creating a package.json file. package.json keeps a track of all the modules used in the project. We will discuss about package.json file later.

Now create another file named index.js.

We will write all our codes in this index.js file and run this file using node command.

Now in this tutorial we will use Express Js. Express is a JavaScript framework used for routing the APIs. Learn more about express here.

Install Express Js by executing the following command from terminal (in the same directory location as before).

npm install --save express

This command will install express in the project.

Now paste the following code in index.js file.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);

Let’s understand what the above code signifies.

var express = require('express');

In this statement an object is created that contains all methods of express module, you just installed.

var app = express();

Here we are initialising a variable app where the express() function is stored. This app variable will be used to get the incoming requests.

app.get('/', function (req, res) {
res.send('Hello World');
});

Here in this upper code get is basically a callback method present in the app object, which is called when a GET request comes. Requests can be of different types. ‘ / ’ signifies the API that this piece of code will execute for. Depending on the APIendpoint this small function will get executed. function(req, res) is basically a function that will get triggered after the callback happens. In simple words, if the APIgets hitted then the lines within the function(req, res) will get executed.

app.listen(3000);

In this line we tell the node script to listen on a port of the local machine. Here we are running on port 3000. Thus all incoming requests on port 3000 will be handled from this script.

Run this script but typing node index.js from the command line in the local directory.

node index.js

To check the output, open the browser and visit http://localhost:3000

For queries reach me out at jitbrahma@gmail.com

--

--