3 回答

TA贡献1827条经验 获得超8个赞
这是因为变量位于处理程序函数内部,每次服务器处理请求时都会重新创建该函数。您必须在全局上下文中声明它:counter
let counter = 0;
setInterval(() => {
counter++;
}, 1000);
http.createServer((req, res) => {
let path = './states/' + counter + '.html';
let readStream = fs.createReadStream(path);
res.writeHead(200,{'Content-type': 'text/html'});
readStream.pipe(res);
}).listen(3000);
或者你可以简单地在前端(HTML文件)上做:
setTimeout(() => {
const currentNum = parseInt(window.location.href.match(/[0-9]+/)[0]);
window.location.href = window.location.href.replace(/[0-9]+/, currentNum + 1);
}, 1000);这是因为变量位于处理程序函数内部,每次服务器处理请求时都会重新创建该函数。您必须在全局上下文中声明它:counter
let counter = 0;
setInterval(() => {
counter++;
}, 1000);
http.createServer((req, res) => {
let path = './states/' + counter + '.html';
let readStream = fs.createReadStream(path);
res.writeHead(200,{'Content-type': 'text/html'});
readStream.pipe(res);
}).listen(3000);
或者你可以简单地在前端(HTML文件)上做:
setTimeout(() => {
const currentNum = parseInt(window.location.href.match(/[0-9]+/)[0]);
window.location.href = window.location.href.replace(/[0-9]+/, currentNum + 1);
}, 1000);

TA贡献1893条经验 获得超10个赞
尝试声明
let readStream = fs.createReadStream('./states/1.html');
在集合区间函数中。我希望这将解决您的问题。

TA贡献1794条经验 获得超8个赞
你可以从前端尝试这个,比如:
setTimeout(() => {
var currentNum = parseInt(window.location.href.match(/[0-9]+/)[0]);
window.location.href = window.location.href.replace(/[0-9]+/, currentNum + 1);
}, 1000);
添加回答
举报