仅在第二个请求中写入页面的响应
问题描述:
var http = require('http');
var fs = require('fs');
var path = process.argv[2];
var str="";
function onRequest(request, response) {
str += "";
console.log("Request received" + path);
fs.readdir(path, function(err, items) {
str += items;
});
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(new Buffer(str).toString());
response.end();
}
http.createServer(onRequest).listen(8000);
上面的代码片段创建一个http服务器,该服务器从用户获取目录路径作为参数。发出http请求以获取目录中可用文件的列表并将其作为响应发回。仅在第二个请求中写入页面的响应
只有在第二个请求中才将响应写入页面。该页面在第一个请求中显示为空。
任何人都可以帮忙。提前致谢!!
答
JavaScript是无阻塞,因此
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(new Buffer(str).toString());
response.end();
将
str += items;
之前它将readdir
后发送响应来执行随着
fs.readdir(path, function(err, items) {
// Handle error
str += items;
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(new Buffer(str).toString());
response.end();
});
。
而在Javascript中,程序不会为每个新请求启动(如在PHP中)。所以你的全局变量将在所有请求之间共享。如果你不希望这样,var str="";
在onRequest
。
如果你有多条路线,你也想看看express之类的东西,因为http
模块不包含路由。
如何使用标准输入读取上述代码的输入 –
stdin有点复杂,因为您不知道是否所有的stdin都读取。看看https://gist.github.com/kristopherjohnson/5065599或https://www.npmjs.com/package/get-stdin – Julian
process.stdin.on('readable',() => { path = process.stdin.read(); console.log(path); });无法阅读使用stdin –