亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

每秒加載新的HTML文件,并設置間隔節點.js

每秒加載新的HTML文件,并設置間隔節點.js

森欄 2022-09-23 10:06:54
我有一個在本地主機上運行的服務器,我希望它每秒顯示一個新的html文件。例如:先 1.html然后是 2.html然后是 3.html依此類推。當我只想顯示 1 時,此代碼有效.htmlhttp.createServer((req, res) => {    let readStream = fs.createReadStream('./states/1.html');    res.writeHead(200,{'Content-type': 'text/html'});    readStream.pipe(res);}).listen(3000);但是,當我嘗試使用setInterval時,我只看到1.html,并且它不會每秒更改為2.html,3.html等等。http.createServer((req, res) => {    let counter = 0;    let readStream = fs.createReadStream('./states/1.html');    setInterval(() => {        let path = './states/' + counter + '.html';        readStream = fs.createReadStream(path);        counter++;    }, 1000);    res.writeHead(200,{'Content-type': 'text/html'});    readStream.pipe(res);}).listen(3000);如何獲取節點.js每秒顯示一個新的 html 文件?
查看完整描述

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);


查看完整回答
反對 回復 2022-09-23
?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

嘗試聲明

    let readStream = fs.createReadStream('./states/1.html');

在集合區間函數中。我希望這將解決您的問題。


查看完整回答
反對 回復 2022-09-23
?
幕布斯7119047

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);


查看完整回答
反對 回復 2022-09-23
  • 3 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號