Creating Web Servers: Node.js
Tags: node, tutorial, javascript
Published: 2020-07-10 18:22:06

---
title: Creating Web Servers: Node.js
published: true
description: Tutorial on creating a web server with Node.js
tags: #nodejs #tutorial #javascript
canonical_url: https://virenb.cc/web-servers-nodejs
//cover_image: https://direct_url_to_image.jpg
---

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](https://en.wikipedia.org/wiki/Web_server "Web server on Wikipedia"), 

> "A **web server** is [server software](https://en.wikipedia.org/wiki/Server_software), or [hardware](https://en.wikipedia.org/wiki/Computer_hardware) dedicated to running this software, that can satisfy [client](https://en.wikipedia.org/wiki/Client_(computing)) requests on the [World Wide Web](https://en.wikipedia.org/wiki/World_Wide_Web). A web server can, in general, contain one or more [websites](https://en.wikipedia.org/wiki/Website). A web server processes incoming [network](https://en.wikipedia.org/wiki/Computer_network) requests over [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) and several other related [protocols](https://en.wikipedia.org/wiki/Communication_protocol).
>
> The primary function of a web server is to store, process and deliver [web pages](https://en.wikipedia.org/wiki/Web_page) to clients.The communication between client and server takes place using the [Hypertext Transfer Protocol (HTTP)](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol). Pages delivered are most frequently [HTML documents](https://en.wikipedia.org/wiki/HTML), which may include [images](https://en.wikipedia.org/wiki/Image), [style sheets](https://en.wikipedia.org/wiki/Style_sheet_(web_development)) and [scripts](https://en.wikipedia.org/wiki/JavaScript) in addition to the text content. "



![Web Server ](//images.ctfassets.net/yzwpq1epaq68/4JsDypI1ZgGkPNA23ZtEs1/cf54b606ee6a84d9052163ab1270dd72/server.png)



# Installing Node

[https://nodejs.org/en/](https://nodejs.org/en/ "node.js")

![Nodejs.org](//images.ctfassets.net/yzwpq1epaq68/3Qs3JcRxZwM5eKATaYk2DD/6511aaacd17a1d246bc1e717b0373916/installing-node-ss.png)


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.

```bash
node -v
// v14.5.0
```

Now that Node.js is installed, we can create a JavaScript file (as done in the terminal)


```bash
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](https://nodejs.org/api/ "Node.JS 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](https://nodejs.dev/learn "Nodejs.dev ").

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')`.'


```javascript
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()](//images.ctfassets.net/yzwpq1epaq68/6lkLPIZHaDI0ofZWZxXaMX/b9bfbd47421aded1c2284272ae8e2d94/createServer-ss.png)


`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`).


```javascript
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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type "MDN Content-Type").

```javascript
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 calling [`response.write(data, encoding)`](https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback) followed by `response.end(callback)`.



Or you can return the data with `response.end()`.


`response.end('<h1>Hello World</h1>');`


or


```javascript
response.write('<h1>Hello World</h1>');
response.end();
```


Our code now looks like:

```javascript
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()](https://nodejs.org/api/net.html#net_server_listen "server.listen() docs")

```javascript
const port = 3001;

server.listen(port, () => {
  console.log(`Server is running on localhost:${port}`);
});
```


Our code should now look like:

```javascript
// 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:

![Hello World](//images.ctfassets.net/yzwpq1epaq68/4mSXEVZ53dESnPxuLex1bO/5ae89c654ebd2af3c186d404227c36ef/hello-word-ss2.png)



That's all! Thank you for reading.



## Links & Resource

[https://nodejs.org/en/](https://nodejs.org/en/ "Node.js Docs")

[https://nodejs.dev/](https://nodejs.dev/ "Learn Node.js")

[https://developer.mozilla.org/en-US/](https://developer.mozilla.org/en-US/ "MDN Docs")

[https://en.wikipedia.org/wiki/Web_server](https://en.wikipedia.org/wiki/Web_server "Wikipedia: Web Server")