每秒加载新的HTML文件,并设置间隔节点.js

我有一个在本地主机上运行的服务器,我希望它每秒显示一个新的html文件。例如:先 1.html然后是 2.html然后是 3.html依此类推。当我只想显示 1 时,此代码有效.html


http.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 文件?


森栏
浏览 110回答 3
3回答

慕仙森

这是因为变量位于处理程序函数内部,每次服务器处理请求时都会重新创建该函数。您必须在全局上下文中声明它:counterlet 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);这是因为变量位于处理程序函数内部,每次服务器处理请求时都会重新创建该函数。您必须在全局上下文中声明它:counterlet 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);

白猪掌柜的

尝试声明    let readStream = fs.createReadStream('./states/1.html');在集合区间函数中。我希望这将解决您的问题。

幕布斯7119047

你可以从前端尝试这个,比如:setTimeout(() => {   var currentNum = parseInt(window.location.href.match(/[0-9]+/)[0]);  window.location.href = window.location.href.replace(/[0-9]+/, currentNum + 1);}, 1000);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript