这是我的第一个名为index5.js
var server = require("./nonblockingserver");
var router = require("./nonblockingrouter");
var requestHandlers = require("./requestHandlers4");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
这是我的第二个名为nonblockingserver.js
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
这是我的第三个名为nonblockingrouter.js
function route(handle, pathname, response) {
console.log("About to route a request for " + 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;
这是我的第三个名为requestHandlers4.js
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
exec("ls -lah", function (error, stdout, stderr) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(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;
当我在浏览器中编写http://localhost:8888/start
时,它应该显示目录中的所有文件,而不是在浏览器上打印任何内容。
答案 0 :(得分:0)
尝试更改此内容,
response.writeHead(200, {"Content-Type": "text/plain"});
要,
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});