Reading and Serving HTML From a File

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 237:- Reading and Serving HTML From a File

To read and serve an HTML file from a Node.js server, we can use the fs (File System) module in Node.js.

First, we need to require the fs module by adding the following code at the top of our server file:

javascriptCopy code

const fs = require('fs');

Then, we can use the fs.readFile() method to read the contents of the HTML file. We need to pass the path of the file and a callback function to fs.readFile(). The callback function will be called when the file is read, and it will receive an error object and the contents of the file as arguments.

Here's an example of reading an HTML file named index.html:

javascriptCopy code

fs.readFile('index.html', (err, data) => {  if (err) {    res.writeHead(404);    res.write('File not found!');  } else {    res.writeHead(200, {'Content-Type': 'text/html'});    res.write(data);  }  res.end(); });

In the above code, we first check if there is an error while reading the file. If there is an error, we send a 404 status code and a message "File not found!" as a response. If the file is successfully read, we set the Content-Type header to text/html and send the contents of the file as the response.

Note that we also call the res.end() method to end the response after writing to the response stream. This is necessary to let the browser know that the response is complete.

Finally, we can start the server and listen for requests by adding the following code:

javascriptCopy code

server.listen(port, hostname, () => {  console.log(`Server running at http://${hostname}:${port}/`); });

Where port and hostname are defined earlier in the code.

28. Node.js Writing - Our First Server

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support