How to Create a Basic Server Using Node.js

Onkar Shingate
Geek Culture
Published in
3 min readMay 17, 2021

Here we are going to understand how to create a basic server using node.js

  1. First, we have to import “HTTP”, ”URL” and “fs” modules into our .js file to use different methods present in that modules. we can import them as below:-
importing modules

2. after importing those three modules, we have to use “createServer()” method of the HTTP module and have to store it into some variable as below. http.createServer() method accepts a call back function as a parameter in which we have to do all things on the server.

creating server

3. Once we created a server we have to add the “.listen” method on the server variable which will accept 1st parameter as port number on which server is going to host and 2nd optional parameter as a callback function . ex:-

server.listen()

“Important TIP”:- handleServer() function must contain “res.end()” .if we didn't use it then the server will never finish loading.and will wait for infinite time to load

4. Now we have to add request and response methods into handleServer function.

here on if statement we are looking for URL “/” which is also known as index URL and if request method is “GET” method and if it is true, then we are telling JS that the content type of item to display is “ HTML” by using statement “res.setHeader(“Content-Type”, “text/html”);”.

after that, we are using the fs module and its createReadStream() method to get data from the original file in the form of small chunks of buffer memory (64bit for node.js) .are we are piping those chunks to display data. statement used to do this is “fs.createReadStream(../../index.html).pipe(res)

In this way we can create very simple server using node.js

“How to harvest queries from given url”

if the URL is like “localhost:3000/about/?username=onkar”. In such a case, we are given a query into URL which we can extract from it. here URL module is very useful. we know URL module gives us “url.parse(givenUrl)” method which is used to parse the given URL.

harvesting query from url

a)here we are parsing the URL into the object and storing it into new variable parsedUrl

b)after parsing we can check the pathname and the given URL. here we can find that pathname does not contain queries that were inside the URL.

c)we can access the queries inside the URL by accessing a key named “query” inside parsedUrl .which is in object form.

d)if we have to display that queries on DOM we can use “JSON.stringify()” method to which we can pass “parsedUrl.queries ” object as a parameter.

--

--