javascript - 在运行nodejs的服务器上调用new Date()时,日期返回服务器启动时的日期

标签 javascript node.js date openshift

在带有 Node 的 OpenShift 服务器上,我的 server.js 有一个 var currentTime = new Date()。当调用它时,我只能得到服务器每次启动的时间。我只是想把日期写成这样:

res.writeHead(200, {'Content-Type': 'text/plain'});
console.log(currentTime);
res.write("[" + currentTime + "] " + "Pages: " + output[0] + ", Requests: " + output[1]);
res.end();
console.log('Response written to the web.');

如何获取实际的当前时间而不是服务器时间?

最佳答案

也许您在服务器启动时缓存 currentTime 而不是创建 每个请求都有新的日期对象?你的代码是这样的吗?

var currentTime = new Date(); // Date object created at server start

function callback (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  console.log(currentTime);
  res.write("[" + currentTime + "] " + "Pages: " + output[0] + ", Requests: " + output[1]);
  res.end();
  console.log('Response written to the web.');
}

require('http').createServer(callback).listen(8080);

考虑将日期创建移到回调中:

function callback (req, res) {
  var currentTime = new Date(); // new date object created on each request
  res.writeHead(200, {'Content-Type': 'text/plain'});
  console.log(currentTime);
  res.write("[" + currentTime + "] " + "Pages: " + output[0] + ", Requests: " + output[1]);
  res.end();
  console.log('Response written to the web.');
}

关于javascript - 在运行nodejs的服务器上调用new Date()时,日期返回服务器启动时的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556216/

相关文章:

javascript - 引用错误 : "Sheets" is not defined

javascript - (.+?) 在正则表达式中的用途

javascript - 如何阻止第三方域名重定向到我在 squarespace 中的网站?有没有相关的脚本?

javascript - 如何在公共(public) View 下隐藏源代码

javascript - 销毁 Node 中的请求

node.js - 解析域时如何处理 CNAME?

javascript - 当 setTimeout < 5 node.js 时会发生什么

sql-server - 将日期从字符串转换为新的日期字段

Excel函数: "Not Isblank" with "Or" and if date is

mysql - 如何从 MySQL 中的日期获取当年的当前周数?