Sebastian
Sebastian

Reputation: 377

node.js webserver does not reload

I'm using this script for my node.js webserver (ubunt):

var util = require('util'),
    http = require('http'),
    fs = require('fs');


fs.readFile('htdocs/index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(80);
    util.puts('> Server is running');
});

I'm starting the script with:

forever start server.js

... and it works.

But it doesn't work If I upload some simple html-files like index.html with a link to test.html.

It only works if I stop and start the script. But the link from index.html to test.html doesn't work.

Upvotes: 0

Views: 339

Answers (1)

Daff
Daff

Reputation: 44205

What you are doing is reading the file and then starting the server which means that the response will stay the same as long as the server is running. To always retrieve the latest version of index.html you need to read it on every request:

var util = require('util'),
    http = require('http'),
    fs = require('fs');


http.createServer(function(request, response) {
    fs.readFile('htdocs/index.html', function (err, html) {
        if (err) {
            throw err; 
        }

        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    });
}).listen(80);
util.puts('> Server is running');

To serve more than just the one file you will need to set up a static webserver e.g. using connect static:

var connect = require('connect');
connect.use(connect.static(__dirname + '/htdocs'))

Upvotes: 1

Related Questions