在登录控制台以进行文件更改之前,一切正常。无需手动重新加载页面就可以将文本文件的内容更新到浏览器中吗?
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
if(q.pathname == "/") {
return res.end("Please request any file");
}
if ( q.pathname == "/target.txt") {
var filename = "C:\\Users\\Hp\\Documents\\Development" + q.pathname;
}
else if(q.pathname == "/target1.txt") {
var filename = "C:\\Users\\Hp\\Documents\\Development\\Node Programs\\file system module" + q.pathname;
}
else {
return res.end("No such file found!");
}
fs.readFile(filename, function(err,data) {
if(err) {
return res.end("404 Not Found");
}
res.writeHead(200,{'Content-Type': 'text/html'});
res.write(data);
res.write("Now watching "+ filename);
console.log("Now watching file");
});
fs.watch(filename, () => {
fs.readFile(filename, function(err,data) {
res.writeHead(200,{'Content-Type': 'text/html'});
res.write(data);
res.write("Now watching "+ filename);
console.log("File changed");
res.write(q.pathname+": File changed!");
res.end();
});
});
}).listen(8080);
答案 0 :(得分:1)
尝试一下:https://www.npmjs.com/package/reload
当您执行以下操作时,自动刷新并在浏览器中重新加载代码 代码更改。不需要浏览器插件。