我正在尝试通过模块 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);
}
});
}
和写文件,写Img方法:
this.writeImg = function (code) {
this.status(code);
this.title = that.protocol + "/" + that.httpVersion + " " + that.statusCode.name + " " + that.statusCode.message + "rn";
this.socket.write(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "rn" + "Content-Length: " + that.headers["Content-Length"] + "rn" + "rn");
}
this.writeFile = function(code,body){
this.status(code);
this.title = that.protocol + "/" + that.httpVersion + " " + that.statusCode.name + " " + that.statusCode.message + "rn";
console.log(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "rn" + "Content-Length: " + that.headers["Content-Length"] + "rn" + body);
this.socket.write(that.title + that.responseTime + "Content-Type:" + that.headers["Content-Type"] + "rn" + "Content-Length: " + that.headers["Content-Length"] + "rn" + "rn" + body);
}
知道我能做些什么来管理文件和图像而不会卡在加载时(顺便说一下,它的本地服务器,所以它应该可以快速工作)?谢谢。
这里的另一个线程最近建议 http://expressjs.com/,一个位于node之上的应用程序框架.js它不仅处理本地资源的查找,还为身份验证,缓存标头和许多其他东西提供过滤器实现(他们称之为中间件)。