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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?