Halnex
Halnex

Reputation: 4526

Node JS server freezes when loading HTML files dynamically

I am trying to load 3 html files dynamically: header.html, search.html and footer.html

I have a render.js file that reads the html files in the view directory.

var fs = require('fs');

function view(templateName, values, response) {
    var content = fs.readFileSync('./views/' + templateName + '.html');

    response.write(content);
}

module.exports.view = view;

and then in my router.js I am calling the html files via the view method

var Profile = require("./profile");
var render = require('./render');

function home(request, response) {
    if(request.url === '/') {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        render.view('header', {}, response);
        render.view('search', {}, response);
        render.view('footer', {}, response);
    }
}

This is app.js which initiates the server

var http = require('http');
var router = require('./router');

http.createServer(function(request, response) {
    router.home(request, response);
    router.user(request, response);
}).listen(3000);
console.log('Server is running at localhost:3000');

The problem is, the Node JS server is freezing and in the Network tab of the dev tooks, it says pending in the status column.

And this is the error I get on the page.

The localhost page isn’t working

localhost unexpectedly closed the connection.

ERR_INCOMPLETE_CHUNKED_ENCODING

However, if I replace the last render.view line which is the footer with a normal response.end('Footer'); then the page loads fine. I can see the html content of header.html and search.html and at the end the word Footer.

If I remove the third line completely, the page doesn't load at all and back to the initial error. If I try it with just 1 line, it also freezes.

No idea what's causing this.

The html files are fairly simple, this is header.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Treehouse Profile</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../assets/css/teamtreehouse.css">
</head>
<body>

This is search.html

<img src="../../assets/img/search.png" alt="Magnifying Glass" id="searchIcon">

<form action="/" method="POST">
    <input type="text" placeholder="Enter a Treehouse username" id="username" name="username">
    <input type="submit" value="search" class="button">
</form>

This is footer.html

</body>
</html>

Upvotes: 0

Views: 268

Answers (1)

Shimon Doodkin
Shimon Doodkin

Reputation: 4569

just add response.end() at the end

Upvotes: 1

Related Questions