Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs - include HTML file by using the filesystem

I am new to web programming and started learning NodeJs. I created a new project just for testing and learning. This is the projects structure

Project

My Server.js contains this code

var http = require('http');
var url = require('url');
var fileSystem = require('fs');

var server = http.createServer(function(req, res) {
  var page = url.parse(req.url).pathname;
  res.writeHead(200, {"Content-Type": "text/html"});

  fileSystem.readFile(getPage(page), null, function(error, data){
    if(error){
      throw error;
    } else {
      res.writeHead(data);
    }
    res.end();
  })
});
server.listen(2312);

function getPage(page){
  var content = "Templates/";
  switch (page) {
    case "/Page1":
        content += 'Page1.html';
        break;
    case "/Page2":
        content += 'Page2.html';
        break;
    case "/Page3":
        content += 'Page3.html';
        break;
    default:
        content += 'Page404.html';
    }
    return content;
}

My html files contain very simple HTML code

Page1

<!DOCTYPE html>
<html>

<head>
  <title></title>
  <link rel="stylesheet" href="Button.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="Btns.js"></script>
</head>

<body>

  <button onclick="loadPage2()">Load Page 2</button>

  <button onclick="loadPage3()">Load Page 3</button>

</body>

</html>

So when trying http://localhost:2312/Page1 I get an invalid status code of 0.

_http_server.js:195 throw new RangeError(Invalid status code: ${statusCode}); ^

RangeError: Invalid status code: 0 at ServerResponse.writeHead (_http_server.js:195:11) at ...\TestProjekt\Server.js:13:9 at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:439:3)

Is it possible to load html files by doing this way?

I know I could use the Express framework but I thought about learning and starting with the native code.

like image 782
peterHasemann Avatar asked Apr 08 '26 13:04

peterHasemann


1 Answers

Change res.writeHead(data); to res.write(data);

writeHead() Sends a response header to the request.

write() Sends data.

The first time response.write() is called, it will send the buffered header information and the first chunk of the body to the client. The second time response.write() is called, Node.js assumes data will be streamed, and sends the new data separately.

like image 163
Harikrishnan Avatar answered Apr 10 '26 01:04

Harikrishnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!