我构建了一个简单的服务器来处理错误(例如,找不到文件),该服务器可以正常工作:
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()的错误?
流可以发出error
事件。您可以侦听此事件,以防止引发错误的默认行为:
raw.on('error', function(err) {
// do something with `err`
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句