#3 Pure NodeJs: return html file (Part 3)
Tags: webdev, node, beginners, tutorial
Published: 2024-02-05 20:05:21

In this tutorial we will continue the [previews article](https://dev.to/basharosman/2-pure-nodejs-simple-server-part-2-32k3) to learn how to serve an html file as response.

programs and versions: 
nodejs: v18.19.0
npm:    v10.2.3
vscode: v1.85.2

should work on any nodejs > 14

### Lets Start:
the code that we used before to serve html string was this: 
```javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<h1>Hello World!</h1>');
});

const PORT = 2121;
server.listen(PORT, 'localhost', () => {
  console.log(`server run on port ${PORT}`);
});

```
we need to use require "fs" core module stands for "File System" so we can get the html file. but first we need to create index.html file in the same folder that we created server.js in it. the html file content will be:

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, 
          initial-scale=1.0" />
    <title>Pure NodeJS</title>
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100vw;
        height: 100vh;
      }
      h1 {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>Hello world!</h1>
  </body>
</html>

``` 
some basic html and add style to center the h1 in the screen and give it blue color.

for the server.js we will require the "fs" module like this:
```javascript
const fs = require('fs/promises');
```
because i love the Promises async/await in the NodeJS es6 and the code will be easier to read i will use the 'fs/promises'.

so now to get and show our index.html file we can do it like this:
```javascript
const server = http.createServer(async (req, res) => {
  try {
    const htmlContent = await fs.readFile('./index.html');
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(htmlContent);
  } catch (error) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`<h1 style="color:red;">${error.message}</h1>`);
  }
});
```
notice that we added the "async" before the (req,res)=>{...}; and i use "try catch" so if there any problem in the code we can send the error message as html red color.

now you can run the server with this code:
```shell
node server.js
``` 
open the browser localhost:2121 and you will find the hello world in the center blue color.

if you want to test if the error happened we can change the html file name to be like "notfoundfile.html" so this file is not found  by the "fs" module and will return error: 
```
ENOENT: no such file or directory, open './notfoundfile.html'
```
note: you need to stop the server with CTRL + c and re start it again.


### the complete code:
```javascript
const http = require('http');
const fs = require('fs/promises');

const server = http.createServer(async (req, res) => {
  try {
    const htmlContent = await fs.readFile('./index.html');
    res.writeHead(200, { 'Content-Type': 'text/html' });

    res.end(htmlContent);
  } catch (error) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`<h1 style="color:red;">${error.message}</h1>`);
  }
});

const PORT = 2121;
server.listen(PORT, 'localhost', () => {
  console.log(`server run on port ${PORT}`);
});
```

### Conclusion:
In this article we show you how to return html file as response using simple pure NodeJs server.

in the next article i will show you how to return Json data as response