我构建了一个处理错误的简单服务器(例如,找不到的文件),工作正常:
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()的错误?
答案 0 :(得分:6)
Streams可以发出error
个事件。您可以侦听此事件以防止抛出错误的默认行为:
raw.on('error', function(err) {
// do something with `err`
});