在运行nodejs的服务器上调用new Date()时,date会在服务器启动时返回

JTu*_*JTu 0 javascript date node.js 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.');
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*ake 5

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

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);
Run Code Online (Sandbox Code Playgroud)

考虑在回调中移动日期创建:

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.');
}
Run Code Online (Sandbox Code Playgroud)