NodeJS is one of the most popular runtime environments for building applications. The NodeJS ecosystem has led to the development of a plethora of libraries and frameworks. By bringing JavaScript to the backend, NodeJS has also transformed the way we build our applications. In this post, we will see how to create a NodeJS server from scratch.
To install NodeJS on your system, please follow the instructions on the official NodeJS website.
1 – Create a NodeJS Server
Once NodeJS is installed on our system, we can create a folder for our first NodeJS project. Within the folder, we need to create a file.
The file can have any name we want. However, as per convention, we usually name it index.js
, server.js
or also, app.js
.
For our example, we will use app.js
.
const http = require('http');
function reqListener(req, res) {
console.log(req);
}
const server = http.createServer(reqListener)
server.listen(3000);
In the first statement, we get access to the http
module. The http
module is one of the core modules that is available as part of NodeJS installation. We can use this module to launch a NodeJS server and send requests to other applications.
Some other important core modules are:
- https – This is to launch a SSL server.
- fs – This core modules enables access to the underlying file system
- path – This module allows us to deal with the operating system’s path.
- os – This module contains functionality to interact with the operating system.
Using the http
module, we call the createServer()
method. Basically, this method returns a server instance.
The method requires a listener function as input. This function takes two inputs – request and response. In our example, we create the reqListener()
function and pass it as input to createServer()
. Within the function, we simply log the request object to the console.
Note that instead of declaring a function like reqListener()
, we can also simply have an anonymous callback function in createServer()
. It will also work similarly.
Lastly, we use server.listen()
to actually start our application. Basically, the listen()
method on the server object starts a process that will not exit immediately but listen to incoming requests. This method takes a couple of optional parameters as input – the port and host. In our case, we just enter port as 3000 and host is automatically taken as the localhost.
2 – NodeJS Program Life Cycle
Let us understand what is happening behind the scenes when we create a NodeJS server.
When we first execute the command node app.js
, a background script is run. It parses our code, registers the variables and functions. Once everything goes fine, it starts the NodeJS event loop.
The NodeJS event loop is special program. Basically, this program keeps on running as long as any event listener is still registered. In our case, the server.listen()
call registers a listener that is never unregistered in the program. Hence, the our NodeJS app will keep on running and wait for any incoming requests.
If we want to explicitly kill the NodeJS server, we can make a call to process.exit()
as below:
const http = require('http');
function reqListener(req, res) {
console.log(req);
process.exit();
}
const server = http.createServer(reqListener)
server.listen(3000);
Basically, this will stop the server process as soon as a request is handled by the listener. Other option to shut down a running server is to hit Ctrl + C
.
3 – NodeJS Request and Response Object
By default, NodeJS provides access to the request and response objects. The request object contains a lot of data and methods. However, it is usually not required to go through all of them.
Few important pieces of data within the request object are as follows:
- req.url – This gives access to the actual URL that was called by the client. If we access,
http://localhost:3000
, thereq.url
contains the value/
or the root path. - req.method – This is the HTTP method of the incoming request.
- req.headers – This object stores the request headers such as Content-Type, Authorization details and so on.
While the request object is full of data, the response object is pretty much empty. However, we can use it to send back responses for incoming requests. We can use methods such as setHeader()
to set response headers. Also, we can return text or HTML data using something like res.write()
.
See below example:
const http = require('http');
function reqListener(req, res) {
console.log(req.url, req.method, req.headers);
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title>Demo Page</title></head>')
res.write('<body><h1>Hello from NodeJS Demo App</h1></body>')
res.write('</html');
res.end();
}
const server = http.createServer(reqListener)
server.listen(3000);
As you can see, we have returned some HTML response. Once we write the response, we have to call res.end()
to inform NodeJS that the response is over. Note that this is a very unwieldy way of returning HTML but it is just a simple example.
Conclusion
In this post, we successfully created a NodeJS server from scratch. In the process, we got some knowledge about the NodeJS core modules and the NodeJS event loop. Also, we played around with NodeJS request and response objects.
If you want to build some bigger applications with NodeJS, check out this post on NodeJS Redis Pub Sub.
In case of any queries or comments on this post, please feel free to mention them in the comments section below.
0 Comments