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);
添加回答
舉報