为什么我不能使用响应?写入fs.readFile
Why can't I use response.write in fs.readFile?
下面是我的代码。
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
path = path.substr(1);
switch(path){
case '':
response.writeHead(200, {'Content-Type':'text/html'});
response.end();
break;
case 'socket.html':
response.write("read file"); //works
fs.readFile(__dirname + '''' + path, function(error, data){
if (error){
response.writeHead(404); //this doesn't work
}
else{
response.writeHead(200, {'Content-Type':'text/html'}); //doesn't work
response.write("OK"); //doesn't work
}
});
response.end();
break;
default:
response.writeHead(404);
response.end();
break;
}
});
服务器监听端口8001,当我访问http://myhost.com:8001/socket.html时,我只能看到"读取文件"。response中的方法似乎在回调函数readFile中被破坏了。有人能告诉我为什么并给我一个解决方案吗?谢谢!(原谅我的英语不好:))
您过早地结束了响应。传递给readFile的函数是一个异步回调函数,它在整个switch语句之后运行。
相关文章:
- 在.csv文件中写入学位符号
- 节点fs.stat名称未定义
- 在node.js中写入ECONNRESET错误和套接字连接检查
- 在页面卸载时写入HTML5 FileSystem API存储
- 根据HTML文件名授予web服务器写入权限
- 如何让Meteor应用程序使用python脚本写入数据库
- 如何同步写入process.stdout
- 函数式javascript读取、异步、写入结果
- html5画布在同一行中写入多个字体
- firebase中有没有一种方法可以防止快速连续写入
- 通过查询替换/写入文件中的代码
- 如何等待PhantomJS的fs.write完成写入
- 乙烯基fs(gump文件流)未完成.dest写入,然后启动回调或promise
- 使用fs.open和fs.write以独占方式写入文件
- 在fs节点js中写入文本文件而不进行覆盖
- 为什么我不能使用响应?写入fs.readFile
- Can多个fs.写入追加到同一文件保证执行顺序
- fs.writeFileSync给出了错误:UNKNOWN,正确的方法使同步文件在nodejs中写入
- 问题写入文件fs.找不到变量:fs
- 为什么下面是fs.writeFile只从最后一个文件写入数据