We're going to explore how to build a web server (software, not physical hardware) with Node.js. Express.js is a commonly used framework with Node.js but we will not be using it for this.
What is a web server? In my own words it is the software that stores and delivers web pages back to the browser or client.
From Wikipedia,
"A web server is server software, or hardware dedicated to running this software, that can satisfy client requests on the World Wide Web. A web server can, in general, contain one or more websites. A web server processes incoming network requests over HTTP and several other related protocols.
The primary function of a web server is to store, process and deliver web pages to clients.The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages delivered are most frequently HTML documents, which may include images, style sheets and scripts in addition to the text content. "
Installing Node
Once installed, you can open your terminal and type out the following command to confirm its installed and you can also see which version of Node.js you're working with.
node -v
// v14.5.0
Now that Node.js is installed, we can create a JavaScript file (as done in the terminal)
touch index.js
The JavaScript file can now be opend with your text/code editor or IDE of choice.
Before we being coding anything, the Node.JS API documentation will be our friend. They are very large and can be overwhelming. A great resource for learning Node.js without combing through all the API documentation is https://nodejs.dev/learn.
We intend on creating an HTTP web server so we can start by looking up at the http module which comes with Node.
'To use the HTTP server and client one must require('http')
.'
const http = require('http');
There is a method on the HTTP module, createServer()
which does exactly what it sounds like, creates an HTTP server.
createServer()
takes in a function, with an IncomingMessage parameter and a ServerResponse parameter. It is common to refer to them as request
(or req
) and response
(or res
).
const http = require('http');
const server = http.createServer((request, response) => {
// Handle request
// Create response
});
After creating server
, we need to determine what to put in our response. Normally, on a GET request, a Status code is returned. From the documentation, we see 200
is the default but we can still explicity state it.
response.statusCode = 200;
One other important piece of the response is the Content-Type
. It will tell the browser what type of content is being sent back (i.e. HTML file, CSS file, JavaScript script).
More to read about Content-Type's on MDN.
const http = require('http');
const server = http.createServer((request, response) => {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
// Send some content
});
We just have to send some actual content back now. There are two ways to send back data with response.
This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method,
response.end()
, MUST be called on each response.If
data
is specified, it is similar in effect to callingresponse.write(data, encoding)
followed byresponse.end(callback)
.
Or you can return the data with response.end()
.
response.end('<h1>Hello World</h1>');
or
response.write('<h1>Hello World</h1>');
response.end();
Our code now looks like:
const http = require('http');
const server = http.createServer((request, response) => {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
response.end('<h1>Hello World</h1>');
});
We have now created our server but we still have one more thing to do. We need to call the method .listen()
. Since we are running this locally, we need to provide a port
and a callback function. Usually, a console.log()
is a good idea to make sure the server is up.
Node.JS API Documentation: server.listen()
const port = 3001;
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
Our code should now look like:
// index.js
const http = require('http');
const server = http.createServer((request, response) => {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
response.end('<h1>Hello World</h1>');
});
const port = 3001;
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
To run the server, in your terminal, enter the command node index.js
.
You should see 'Server is running on localhost:3001'. You can open your browser to localhost:3001
and you should see:
That's all! Thank you for reading.
Top comments (0)