【问题标题】:read static files on Node.js在 Node.js 上读取静态文件
【发布时间】: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


    【解决方案1】:

    最近这里的另一个线程建议http://expressjs.com/,这是一个基于 node.js 的应用程序框架,它不仅处理本地资源的查找,还提供过滤器实现(他们称之为中间件)用于身份验证、缓存标头和许多其他的东西。

    【讨论】:

    • 我知道 express,但正如我所说,我正在尝试通过模块 NET 构建自己的静态 Web 服务器 :) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2013-08-09
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多