javascript - 如何在 Node.js 中处理 fs.createReadStream() 的错误?

标签 javascript node.js

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

    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() 的错误?

最佳答案

Streams 可以发出一个error 事件。您可以监听此事件以防止引发错误的默认行为:

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

关于javascript - 如何在 Node.js 中处理 fs.createReadStream() 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640022/

相关文章:

node.js - Node +测试: how to mock api using nock

javascript - 在通用错误处理函数中获取失败请求的详细信息

javascript - 在 Vue.js 组件中以编程方式应用过滤器

javascript - R Shiny + plotly : change color of a trace with javascript without affecting markers and legend in multiple plots

node.js - Mongoose - 从现有数据库数据创建模型

javascript - Meteor.js 中模板助手和模板变量的区别

javascript - NodeJS 事件循环多重请求

javascript - 如何编辑 URL 中的部分 anchor

node.js - Node-Redis psubscribe 带有自定义消息

node.js - Angular JWT 配置文件用户(获取 json 字段)