繁体   English   中英

在Node.js上读取静态文件

[英]read static files on Node.js

我正在尝试通过模块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);
}

任何想法我该怎么办才能管理文件和图像而不会在网络上挂载(顺便说一下,它是本地服务器,所以它应该工作很快)?谢谢。

这里的另一个线程最近建议使用http://expressjs.com/ ,这是一种在node.js之上的应用程序框架,该框架不仅处理本地资源的查找,而且还提供用于身份验证的过滤器实现(它们称为中间件),缓存头,还有很多其他事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM