修改系统时区后Node.js代码未同步更新时区问题求助
Node.js服务器时区变更后需重启才生效的问题解决
我完成了ITE404《Web应用编程》课程的课堂作业:用Node.js搭建HTTP服务器,返回包含课程信息的HTML页面,页面标题为我的姓名加AUIS邮箱,并且根据请求时间切换主题——7:00-19:00使用亮色主题,其余时间使用暗色主题。但遇到一个问题:修改电脑系统时区后,代码仍然沿用旧时区的时间进行主题判断,必须重启服务器才会生效,比如从巴格达时区改为美国时区后,代码还是按巴格达时间处理请求。
相关代码
Node.js服务器代码
const http = require("http"); const fs = require("fs"); let fileContent; const server = http.createServer((req, res) => { const date = new Date(); console.log(new Date().getMinutes()); const time = date.getHours(); if (time >= 7 && time < 19) fileContent = fs.readFileSync("./white.html"); else fileContent = fs.readFileSync("./dark.html"); res.write(fileContent); res.end(); }); server.listen(80);
暗色主题HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>mohammed sarhad ahmed ms21126@auis.edu.krd</title> <style> body { color: white; background-color: black; } table, td, th { border: 1px solid white; border-collapse: collapse; } </style> </head> <body> <table> <tr> <th>course title</th> <th>meeting time</th> <th>meeting location</th> <th>course description</th> </tr> <tr> <td>ITE404 – Web Application Programming</td> <td>Mondays and Wednesdays: from 09:45 to 11:15</td> <td>B-F1-16</td> <td> This course introduces students to Web server programming and scripting. It concentrates on familiarizing students with a server-side programming language such as PHP. Students will learn valuable skills necessary for developing HTTP-based applications. This course builds on ITE304, Fundamentals of Web Systems, to introduce the students to deeper understandings of dynamic Web systems. The course starts by introducing server-side programming fundamentals such as cookies, sessions and HTTP methods handling. Through examples, students will engage in building database-driven applications. Advanced topics such as RESTful web services, rich client integration, and web performance optimization are also well covered in this course. </td> </tr> </table> </body> </html>
亮色主题HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>mohammed sarhad ahmed ms21126@auis.edu.krd</title> <style> body { color: black; background-color: white; } table, td, th { border: 1px solid black; border-collapse: collapse; } </style> </head> <body> <table> <tr> <th>course title</th> <th>meeting time</th> <th>meeting location</th> <th>course description</th> </tr> <tr> <td>ITE404 – Web Application Programming</td> <td>Mondays and Wednesdays: from 09:45 to 11:15</td> <td>B-F1-16</td> <td> This course introduces students to Web server programming and scripting. It concentrates on familiarizing students with a server-side programming language such as PHP. Students will learn valuable skills necessary for developing HTTP-based applications. This course builds on ITE304, Fundamentals of Web Systems, to introduce the students to deeper understandings of dynamic Web systems. The course starts by introducing server-side programming fundamentals such as cookies, sessions and HTTP methods handling. Through examples, students will engage in building database-driven applications. Advanced topics such as RESTful web services, rich client integration, and web performance optimization are also well covered in this course. </td> </tr> </table> </body> </html>
问题原因
Node.js在启动时会读取系统时区信息并缓存,后续即使系统时区变更,new Date()创建的日期对象仍会使用启动时缓存的时区,所以必须重启服务器才能更新时区配置。
解决方法
1. 实时获取系统时区(无需重启)
通过调用系统命令或读取系统文件的方式,在每次请求时实时获取当前系统时区,再基于该时区计算当前小时数。以下是跨平台的实现示例:
const http = require("http"); const fs = require("fs"); const { execSync } = require("child_process"); const server = http.createServer((req, res) => { // 实时获取系统时区 let timeZone; try { if (process.platform === "win32") { // Windows系统获取时区 timeZone = execSync("tzutil /g", { encoding: "utf8" }).trim(); } else { // Linux/macOS系统获取时区 timeZone = execSync("date +%Z", { encoding: "utf8" }).trim(); } } catch (err) { console.error("获取时区失败:", err); // fallback到默认的resolved时区 timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; } // 根据实时时区获取当前小时 const currentHour = parseInt(new Date().toLocaleTimeString("en-US", { timeZone, hour12: false, hour: "2-digit" }), 10); const fileContent = currentHour >=7 && currentHour <19 ? fs.readFileSync("./white.html") : fs.readFileSync("./dark.html"); res.write(fileContent); res.end(); }); server.listen(80);
2. 基于UTC时间或指定时区判断(更稳定)
如果不需要依赖系统时区,而是想固定使用某个特定时区(比如课程所在的巴格达时区),可以基于UTC时间进行计算。巴格达时区为UTC+3,所以UTC时间4:00-16:00对应巴格达时间7:00-19:00:
const http = require("http"); const fs = require("fs"); const server = http.createServer((req, res) => { // 获取UTC小时数 const utcHour = new Date().getUTCHours(); // 对应巴格达时区的7-19点 const isDaytime = utcHour >=4 && utcHour <16; const fileContent = isDaytime ? fs.readFileSync("./white.html") : fs.readFileSync("./dark.html"); res.write(fileContent); res.end(); }); server.listen(80);
额外优化建议
- 避免每次请求都读取HTML文件,可以将文件内容缓存到内存中,只有当文件修改时再重新读取,提升服务器性能。
- 将主题样式抽离为独立的CSS文件(比如
light.css和dark.css),只维护一个HTML文件,通过动态引入不同的CSS来切换主题,减少代码冗余。
内容的提问来源于stack exchange,提问作者Mohammed Sarhad Ahmed
相关产品推荐
相关产品推荐

