【问题标题】:Restart node server automatically using setInterval使用 setInterval 自动重启节点服务器
【发布时间】:2021-05-23 10:10:49
【问题描述】:

我创建了一个节点服务器,它调用 API 并在 index.js 中显示数据。我希望节点服务器 (app.js) 自动重新启动,以便 API 调用每 10 秒左右刷新一次,并且数据始终是最新的。

是否可以将 app.js 的整个代码包装在一个函数中并使用 setInterval 或 setTimeout(如果发生更改,也可以永远使用 node 来重新启动服务器)?还是我需要使用 crontab 等调度程序?

仅供参考:我对编程主题完全陌生,因此我将不胜感激任何帮助和建议。

app.js 看起来像这样:

const something = require("some node module");
async () => {
    const connection = new something({
        email: "email",
        password: "password",
        region: "us",
    });

    const temperature = await connection.getDeviceCurrentTemperature("some ID");
    const humidity = await connection.getDeviceCurrentHumidity("some ID");

    const express = require("express");
    const app = express();

    var bodyParser = require("body-parser");

    app.use(express.static("public"));

    app.set("view engine", "ejs");
    app.set("views", __dirname + "/views");

    app.use(bodyParser.urlencoded({ extended: false }));

    app.get("/", (req, res) => {
        res.render("index", { temp: temperature.temperature, hum: humidity.humidity });
    });

    app.listen(8080, () => {
        console.log("Temperature: " + temperature.temperature + " °C, Humidity: " + humidity.humidity + " %");
    });
};

提前谢谢!

【问题讨论】:

  • 为什么要重启?在每个GET / 调用中读取并响应当前温度并让服务器保持运行不是更好吗?
  • @ΔO'deltazero',怎么办?有什么提示吗?
  • 看看我更新的答案:)

标签: node.js cron settimeout setinterval


【解决方案1】:

只需拨打GET / 即可获取温度和湿度。这是一个盲码,希望它有效

const something = require('some node module'),
      express = require('express'),
      app = express()
      connection = new something({
          email: 'email',
          password: 'password',
          region: 'us',
      })

app.use(express.static('public'))
app.set("view engine", "ejs")
app.set("views", __dirname + "/views")

app.get("/", async (req, res) => {
  res.render("index", {
    temp:   await connection.getDeviceCurrentTemperature('some ID'),
    hum:    await connection.getDeviceCurrentHumidity('some ID')
  })
})

app.listen(8080, () => console.log('server running'))

或者,您可以在不加载数据的情况下在/ 上加载索引,然后在间隔内获取带有 json 数据的 /api,这样您的页面就会获取当前数据(每 10 秒左右)而无需重新加载。

app.get('/api', async (req, res) => {
  // parallel loading
  const [ temp, hum ] = await Promise.all([
    connection.getDeviceCurrentTemperature('some ID'),
    connection.getDeviceCurrentHumidity('some ID')
  ])
  
  res.json({ temp, hum })
})

app.get('/', (req, res) => res.render("index"))

【讨论】:

  • RE 第一个示例:不显示 index.ejs 中 API 调用的值 RE 第二个示例:仅显示带有值的 JSON 字符串
  • @PhGa90 我认为回答的用户已经提供了足够的示例,您应该尝试理解发布的代码并从中推断以应用您自己的解决方案
  • @PhGa90, Ad 1) 它应该传递数据,如果不传递则需要更多信息。广告 2) JSON 是重点 :-) 您应该使用客户端 javascript 将 fetch 它添加到您的网站
【解决方案2】:

您无需重新启动整个服务器即可执行此操作。您的app.listen 仅在您的服务器启动时执行一次。但是每次客户端向路径“/”发送 GET 请求时都会调用您的 app.get。

你能做的就是移动

    const temperature = await connection.getDeviceCurrentTemperature('some ID');
    const humidity = await connection.getDeviceCurrentHumidity('some ID');

在您的 app.get 内部

app.get("/", (req, res) => {
    // you could even parallelize these calls
    const temperature = await connection.getDeviceCurrentTemperature('some ID');
    const humidity = await connection.getDeviceCurrentHumidity('some ID');

    res.render("index", {temp: temperature, hum: humidity});
}); 

这样每次连接都会刷新数据。

【讨论】:

  • 在你的箭头函数之前你会错过一个async,但这似乎是正确的解决方案
猜你喜欢
  • 2013-05-09
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 2017-09-11
  • 2018-04-05
  • 2014-01-21
  • 2012-08-23
相关资源
最近更新 更多