Я построил простой сервер, обрабатываются ошибки (файлы, которые не найдены, например), который работает отлично:Как обрабатывать ошибки для fs.createReadStream() в 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()?
Прохладный, я думал о чем-то подобном, но не видел его в документах. –
[Здесь] (http://nodejs.org/api/stream.html#stream_event_error) является ссылкой на документ события ошибки чтения. – mscdex