Serving HTML!

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 236:- Serving HTML!

To serve an HTML file, you can use the fs (file system) module in Node.js to read the contents of the HTML file and then serve it as a response to the client's request.

Here is an example code snippet that serves an index.html file using the http module in Node.js:

javascriptCopy code

const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => {  // Read the index.html file  fs.readFile('index.html', (err, data) => {    if (err) {      res.writeHead(500, { 'Content-Type': 'text/html' });      res.end(`<h1>Error loading index.html</h1><p>${err}</p>`);    } else {      res.writeHead(200, { 'Content-Type': 'text/html' });      res.end(data);    }  }); }); server.listen(3000, () => {  console.log('Server is listening on port 3000'); });

In this example, we first create an HTTP server using the createServer() method of the http module. The server listens on port 3000 for incoming requests.

When a client makes a request to the server, the server's callback function is executed. Inside the callback function, we read the contents of the index.html file using the fs.readFile() method.

If an error occurs while reading the file, we send an error response to the client with a status code of 500 and an error message. Otherwise, we send the contents of the file as a response with a status code of 200 and the Content-Type header set to text/html.

Finally, we start the server by calling the listen() method and passing the port number to listen on.

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