无法在控制台上的目录中输出文件?

时间:2014-05-02 12:10:54

标签: javascript node.js

这是我的第一个名为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时,它应该显示目录中的所有文件,而不是在浏览器上打印任何内容。

1 个答案:

答案 0 :(得分:0)

尝试更改此内容,

response.writeHead(200, {"Content-Type": "text/plain"});

要,

response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});