skip to Main Content
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


  1. 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 file

    const server = http.createServer(function (req, res) {
      fs.readFile("./home.html", function (err, data) {
        if (err) {
          res.writeHead(404);
          console.log(err);
        } else {
          res.writeHead(200, { "Content-Type": "text/html" });
          console.log(data);
          res.write(data);
        }
        res.end();
      });
    });
    
    Login or Signup to reply.
  2. you are ending the response before writing the data.

    here is a full working code:

    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);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search