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

when calling new Date() on server running nodejs, date returns when server was started

在我的带有 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.');
}