app.js 、 server.js 和 router.js 是 3 个文件
app.js
var server = require('./server');
var router = require('./router'); //here we are requiring the module
server.start(router.route);
服务器.js
var http = require("http");
var url = require("url");
function start(route){
function onRequest(request, response) {
var pathname = url.parse(request.url);
console.log("request for " + pathname + " recieved");
//in this line we are using route function
route(pathname); //which is in router.js
//why are we not requiring the module ie require('./router')
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8080);
console.log("Server has started.");
}
exports.start = start;
路由器.js
function route(pathname){
console.log("About to route a request for "+pathname);
}
exports.route = route;
为什么我们不在 server.js 文件中要求 router.js (require('./router');
)
最佳答案
正如您所见,server.js 不需要 paths.js 文件,因为它是作为 server.js 上 start 函数的参数传递的。
话虽如此,我在您的代码中看到一个错误,server.js 上的启动函数应该有一个“route”参数。
然后,当您实例化 app.js 时,您需要两者,但是当您调用 start 并发送该参数时,之后您不需要再次导入 paths.js,因为它已经作为引用存在。
如果这能回答您的问题,请告诉我。
最好, 达里奥
关于javascript - 我无法遵循 Node 初学者书中的以下代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941045/