首次编写模块化JavaScript代码(从Java服务器代码慢慢转换为Node JS)时,我很难理解为什么这段代码无法正常工作。
节点服务器代码:
const wceTimer = require('./myTimer');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log('Server running at http://' + hostname + ':' + port + '/');
console.log(typeof wceTimer);
console.log(typeof wceTimer.getTime);
});
这是我的模块代码:
var myTimer = (function (){
var currentTimeMS = -1;
var timerInterval;
function getTime(){
return currentTime;
}
function getTimeFormatted(){
if(currentTime <= 0) {
return "undefined";
} else {
return new Date(currentTimeMS).toUTCString();
}
}
function advanceTime(){
if(currentTime <= 0) {
this.currentTimeMS = 946684800000;
} else {
this.currentTimeMS = this.currentTimeMS + 1000;
}
}
function startTimer(){
timerInterval = setInterval(advanceTime, 3000);
}
function stopTimer(){
clearInterval(timerInterval);
}
return {
startTimer: startTimer,
stopTimer: stopTimer,
getTime: getTime,
getTimeFormatted: getTimeFormatted
};
})();
为什么server.listen方法中的第3行失败并且未定义? 为什么我不能在浏览器中使用开发者控制台来调用myTimer上的函数?
答案 0 :(得分:3)
您的模块没有导出任何内容:
module.exports = myTimer;