const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('home.html', function(err, data) {
if (err) {
res.writeHead(404);
}
else {
res.write(data);
}
});
res.end();
});
server.listen(port, function(error) {
if (error) {
console.log(error);
}
else {
console.log('Server is listening on port ' + port + ' at http://localhost:' + port);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Hello
</body>
</html>
when i run this and go onto the local server there is no text on the screen even thought it should say ‘Hello’ as thats what ive wrote in the home.html file
ive just installed node js today and dont know how it works much but i still think that this should work
2
Answers
You are calling res.end outside your
fs.readFile
callback which is signaling the end of the request, and the it sends a response to the user before you finish reading/writing the fileyou are ending the response before writing the data.
here is a full working code: