在带有 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/