为了账号安全,请及时绑定邮箱和手机立即绑定

每秒加载新的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条经验 获得超7个赞

这是因为变量位于处理程序函数内部,每次服务器处理请求时都会重新创建该函数。您必须在全局上下文中声明它: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 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信