首页 > 解决方案 > 节点js应用程序不断加载

问题描述

Html 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />

    <title>Weather</title>
  </head>
  <body>
    <div
      class="container text-center"
      style="background-color: teal; color: white"
    >
      <h3>Weather</h3>
      <p class="time" id="time">{%time%}</p>
      <h3 id="city">{%location%}, {%country%}</h3>
      <h1 class="temp" id="temp">{%tempval%}</h1>
    </div>
    <script
      src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
      integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
      integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
      integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
      crossorigin="anonymous"
    ></script>
    <script src="./script.js"></script>
  </body>

</html> 

JavaSCript 文件:

const http = require("http");
const fs = require("fs");
const requests = require("requests");

const homeFile = fs.readFileSync("home.html", "utf-8");

//time

const getDate = () => {
  let currentTime = new Date();
  var weekday = new Array(7);
  weekday[0] = "SUN";
  weekday[1] = "MON";
  weekday[2] = "TUE";
  weekday[3] = "WED";
  weekday[4] = "THU";
  weekday[5] = "FRI";
  weekday[6] = "SAT";

  var weekDay = weekday[currentTime.getDay()];
  console.log(weekDay);
  return weekDay;
};
let CurTime = "";
function getActualTime() {
  let x = new Date();
  let hours = x.getHours();
  let minutes = x.getMinutes();
  console.log(`${hours}:${minutes}`);
  CurTime = `${hours}:${minutes}`;
  return CurTime;
}
let time = `${getDate()} | ${getActualTime()}`;

// temp and all
const replaceVal = (tempVal, originalVal) => {
  let temperature = tempVal
    .replace("{%tempval%}", `${(originalVal.main.temp - 273.15).toFixed(2)} °C`)
    .replace("{%location%}", originalVal.name);
  temperature = temperature.replace("{%country%}", originalVal.sys.country);
  temperature = temperature.replace("{%time%}", time);
  return temperature;
};

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    requests(
      "http://api.openweathermap.org/data/2.5/weather?q=Chakdaha&appid=3804d124fa934e781f13a0fe88c6780e"
    )
      .on("data", function (chunk) {
        const objData = JSON.parse(chunk);
        const arrData = [objData];
        // console.log(`${arrData[0].main.temp - 273.15}`);
        const realTimeData = arrData
          .map((val) => replaceVal(homeFile, val))
          .join("");
        res.write(realTimeData);
        res.end();
        // console.log(realTimeData);
      })
      .on("end", function (err) {
        if (err) return console.log("connection closed due to errors", err);
        res.end();
      });
    // res.send({ status: 200 });?
  }
});
server.listen(8000, "127.0.0.1", () => {
  console.log("Server Started");
});

在服务器启动时,服务器会不断重新加载。服务器重新加载不会停止。我也尝试在 .on("end",function(){}) 之外提供 res.end() 方法,但重新加载似乎并没有停止。我可以看到内容,但重新加载会影响某些功能,例如添加更多值。nodemon 运行良好,但现在连续重新加载似乎会影响。请为此提供修复程序。我想建议你复制这些代码并用 nodemon 运行它,看看你的电脑是否发生了同样的问题。它经常取笑我。

标签: javascriptnode.js

解决方案


推荐阅读