DEV Community

Bashar
Bashar

Posted on • Updated on

#3 Pure NodeJs: return html file (Part 3)

In this tutorial we will continue the previews article 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:

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}`);
});

Enter fullscreen mode Exit fullscreen mode

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:

<!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>

Enter fullscreen mode Exit fullscreen mode

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:

const fs = require('fs/promises');
Enter fullscreen mode Exit fullscreen mode

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:

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>`);
  }
});
Enter fullscreen mode Exit fullscreen mode

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:

node server.js
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

note: you need to stop the server with CTRL + c and re start it again.

the complete code:

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)