【发布时间】:2014-02-06 12:39:24
【问题描述】:
我正在尝试通过模块 NET(带套接字)构建自己的静态 Web 服务器, 我想为文本文件(html,js,css ...)编写响应和为img文件(jpg,gif ....)编写响应,
我试图用 createReadStream 和 readFile 来做,它可以工作,但它一直卡在加载中, 而且图片有时不工作...
FS.stat(fileSystemAddress + request.fileName, function (err, stat) {
if (err) {
// Error handling
} else {
if (typeImg[request.fileType] != undefined) {
response.headers['Content-Length'] = stat.size;
response.headers['Content-Type'] = typeImg[request.fileType];
response.writeImg(200);
var fileStream = FS.createReadStream(fileSystemAddress + request.fileName);
fileStream.pipe(response.socket, {
end: false
});
}
}
});
if (typeFile[request.fileType] != undefined) {
FS.readFile(fileSystemAddress + request.fileName, 'utf8', function (err,data) {
if (err) {
// Error handling
} else {
response.headers['Content-Length'] = data.length;
response.headers['Content-Type'] = typeFile[request.fileType];
response.writeFile(200,data);
}
});
}
还有 writeFile、writeImg 方法:
this.writeImg = function (code) {
this.status(code);
this.title = that.protocol + "/" + that.httpVersion + " " + that.statusCode.name + " " + that.statusCode.message + "\r\n";
this.socket.write(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "\r\n" + "Content-Length: " + that.headers["Content-Length"] + "\r\n" + "\r\n");
}
this.writeFile = function(code,body){
this.status(code);
this.title = that.protocol + "/" + that.httpVersion + " " + that.statusCode.name + " " + that.statusCode.message + "\r\n";
console.log(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "\r\n" + "Content-Length: " + that.headers["Content-Length"] + "\r\n" + body);
this.socket.write(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "\r\n" + "Content-Length: " + that.headers["Content-Length"] + "\r\n" + "\r\n" + body);
}
知道我可以做些什么来管理文件和图像,而不会让网络卡在加载上(顺便说一下,它的本地服务器,所以它应该可以快速运行)?谢谢。
【问题讨论】:
标签: javascript node.js http web stream