我是 NodeJS 的新手。
我正在阅读这本书来学习它。
我在请求处理程序模块之一中使用以下代码。基本上,当我收到来自浏览器的请求时,我会调用此函数并在屏幕上显示的窗口中获取“DIR”命令的内容。
index.js 文件是我作为 webapp 运行的文件
这是index.js
var server = require("./server.js");
var router = require("./router.js");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
这是server.js 服务器文件将请求发送到路由器
var http = require("http");
var url = require("url");
function start(route, handle)
{
function onRequest(request, response)
{
//console.log("Request recieved!");
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " has been recieved");
response.writeHead(200, {"Content-Type": "text/plain"});
route(handle, pathname, response);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server started!");
}
exports.start = start;
这是router.js 这是使用在index.js中创建的句柄的路由器(用于将请求映射到它们各自的处理程序)。
function route(handle, pathname, response)
{
console.log("About to route the request " + pathname);
if(typeof handle[pathname] == 'function')
{
handle[pathname](response);
}
else
{
console.log("No request handler found for " + pathname);
response.writeHead(404,{"Content Type": "text/plain"});
response.write("404 not found");
response.end();
}
}
exports.route = route;
最后这是处理请求的地方,在requestHandlers.js 在这里,看起来 console.log 语句工作正常,但 response.write 语句没有。
var exec = require("child_process").exec;
function start(response)
{
console.log("Request handler 'start' was called.");
exec("dir", function(error, stdout, stderr) {
response.writeHead(200,{"Content Type": "text/plain"});
response.write("Hello Upload!");
response.write(stdout);
response.write("Hello!");
console.log(stdout);
response.end();
});
}
function upload(response)
{
console.log("Request handler 'upload' was called.");
response.writeHead(200,{"Content Type": "text/plain"});
response.write("Hello Upload!");
response.end();
}
exports.start = start;
exports.upload = upload;
任何帮助将不胜感激