If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.