【问题标题】:How do I handle errors for fs.createReadStream() in Node.js?如何处理 Node.js 中 fs.createReadStream() 的错误?
【发布时间】:2014-12-24 16:55:16
【问题描述】:

我构建了一个简单的服务器来处理错误(例如,未找到的文件),它工作正常:

    fs.readFile(fullPath, function(err, data) {

        // If there is an error, return 404
        if (err) {
            res.writeHead(404);
            res.end();
            debug.log("File denied: " + fullPath);
        } else {
            var length      = data.length;
            var extension   = getExtension(path);
            var type        = getType(extension);

            // If the type doesn't match a MIME type that this app serves, return 404
            if (!type) {
                res.writeHead(404);
                res.end();
                debug.log("File denied: " + fullPath);

            // Otherwise, serve the file
            } else {
                res.writeHead(200, {
                    'Content-Length' : length,
                    'Content-Type' : type
                });
                res.write(data);
                res.end();
                debug.log("File served: " + fullPath);
            }
        }
    });

但我决定要支持压缩,所以我需要使用fs.createReadStream() 来读取文件,就像我正在查看的这个示例一样:

//Check request headers
var acceptEncoding = req.headers['accept-encoding'];
if (!acceptEncoding) {
    acceptEncoding = '';
}

var raw = fs.createReadStream(fullPath);

// Note: this is not a conformant accept-encoding parser.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (acceptEncoding.match(/\bdeflate\b/)) {
    response.writeHead(200, { 'content-encoding': 'deflate' });
    raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
    response.writeHead(200, { 'content-encoding': 'gzip' });
    raw.pipe(zlib.createGzip()).pipe(response);
} else {
    response.writeHead(200, {});
    raw.pipe(response);
}

所以我的问题是我试图弄清楚如何将我的错误处理合并到流方法中,因为fs.createReadStream() 不采用回调函数。

如何处理 Node.js fs.createReadStream() 的错误?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    流可以发出error 事件。你可以监听这个事件来防止默认的抛出错误的行为:

    raw.on('error', function(err) {
      // do something with `err`
    });
    

    【讨论】:

    • 酷,我在想类似的东西,但在文档中没有看到。
    • Here 是可读流错误事件文档的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    相关资源
    最近更新 更多