My First Node JS Program

In this blog

I will showcase how to install nodeJS and how to create a simple HTTP server which will return Hello World! .

For context I am documenting back-end development journey and this is second blog in the series.

but first...

What is HTTP ?

HTTP (Hyper Text Transfer Protocol) is something we experience everyday . It is a foundation for modern web pages. It is a application layer protocol which is the top most layer of OSI and TCP/IP Model.

To learn more checkout my other blog on Computer Networks

What is in an HTTP request?

An HTTP request is the way Internet communications platforms such as web browsers ask for the information they need to load a website.

Each HTTP request made across the Internet carries with it a series of encoded data that carries different types of information.

Let's first create a simple HTTP server with NodeJS

Setup your node file using npm init or npm init -y for selecting all the defualt options which can be changed in /package.json file.

To create a HTTP server first we need to import HTTP module .

const http = require('http')

After importing http we need to create a server to do that we can use createServer method

const app = http.createServer

This method accepts a callback function which has two parameter res and req they stand for respond and request respectively. To return something or to GET something from our server we need to use .end method to return something it can be a html, json or a simple string.

const app = http.createServer((req,res)=>{ res.end('Hello World') })

After this we need to specify a port and where server will listen to the request we just made above.

app.listen(3000,()=>{
console.log("Server is running on port 3000")
})

Here, we used a listen method with our server and passed a callback function and a port, This port is where we will be seeing our content we have sent to http. In that we are just console logging a message which say's server is running on that port.

Now if we check our browser ....

Sweet ! ,

This is how I created my first ever NodeJS program.

In the next blog,

We will discuss more about NodeJS and its modules. Thanks for reading