简体   繁体   English

node.js Web服务器不会重新加载

[英]node.js webserver does not reload

I'm using this script for my node.js webserver (ubunt): 我正在为我的node.js Web服务器使用此脚本(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. 但是,如果我上传了一些简单的html文件(如index.html)并带有指向test.html的链接,则该方法无效。

It only works if I stop and start the script. 它仅在我停止并启动脚本后才有效。 But the link from index.html to test.html doesn't work. 但是从index.html到test.html的链接不起作用。

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: 要始终获取index.html的最新版本,您需要在每次请求时都阅读它:

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 eg using connect static : 要提供多个文件,您需要设置一个静态网络服务器,例如,使用connect static

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM