我正在尝试通过模块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);
}
任何想法,为了管理文件和图像,我可以做些什么,而不会阻止网络加载(顺便说一下它的本地服务器,所以它应该快速工作)?谢谢。
答案 0 :(得分:0)
这里的另一个线程最近建议http://expressjs.com/,一个位于node.js之上的应用程序框架,它不仅处理本地资源的查找,还提供过滤器实现(它们称之为中间件)用于身份验证,缓存头,还有很多其他的东西。