Creating Node.js Server

Amritpal Singh
3 min readMar 9, 2020

--

Hello Everyone,

Today I will be talking about creating a server with Node.js. The rising popularity of JavaScript has brought a lot of changes in web development. We can run Javascript on the server-side, as well as in the browser. Node is open-source and completely free. Using Node we can build back end services such as API (APPLICATION PROGRAM INTERFACE), which powers the front end (client-side). Node is easy to get started as well as building fast and highly scalable applications.

Let us get started with that.

First, download and install Node → https://nodejs.org/en/

To insure if Node was installed successfully, 
go to terminal and write node -v, If you v11.0.0 or similar
that means node was installed successfully

Now that we have installed Node.js, open your text editor and create a file called example.js or whatever you want to call, must have .js extension.

  1. Inside the example.js, in order to create our server, we have to require a library called http.
  2. Next, we need to create a variable for our port.
Step 1 and 2

3. Creating server, make a const of nodeServer (see the image below)

Line 4, we are using http library and called createServer method. That method takes a single function which has two parameters called request and response. Next, on line 8, we set up the server so it will listen on the port we wanted to. We can use the line 4 nodeServer object and call .listen method and write the following.
.listen takes 2 parameters, one the port and the second a function. The function gets called when you start your server. If you encounter an issue error log will get called, otherwise “Successfully Running On Port 3000
Finally, let's finish the nodeServer on line 4 at the moment its empty, the user will not get any response. 
On-Line 5 we are returning a response to every user the access our server. To do that we use the response object that it passed (line 4) into this function. We can write response.write(“TESTING”) or whatever you want to write. Then to end a response we use response.end().

We are all done lets start are server by going to the terminal

node and the filename.js → node example.js

node example.js
on internet browser localhost:3000, 3000 is the port we assigned in our application.

if you want to end the server simply write control + c.

There you have it. I hope you found this blog helpful. If you’re having any difficulty or need more explanation, I’m more than happy to help you. Please connect with me on LinkedIn or my email is singhamritpal49@gmail.com.

Happy Coding :)

Reference:

--

--