无法从node.js程序获取输出?

时间:2014-05-02 07:15:35

标签: javascript node.js

这是我的第一个名为serverpaths.js

的文件
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;

这是我的第二个名为router.js

的文件
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;

这是我的第三个名为index1.js

的文件
var server = require("./serverpaths");
var router = require("./router");
server.start(router.route);

输出应为

Server has started
Request for /foo received. 
About to route a request for /foo

但我得到了输出

Server has started
Request for /foo received

我不知道为什么我没有从路由器获得输出,即About to route a request for /foo.

1 个答案:

答案 0 :(得分:0)

您需要在某个时刻调用您正在传递给启动函数的函数。

var http = require("http");
var url = require("url");

function start(route) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    route(pathname);
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;