I built a simple server that handled errors (files that were not found, for example) that worked fine:
fs.readFile(fullPath, function(err, data) {
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 (!type) {
res.writeHead(404);
res.end();
debug.log("File denied: " + fullPath);
} else {
res.writeHead(200, {
'Content-Length' : length,
'Content-Type' : type
});
res.write(data);
res.end();
debug.log("File served: " + fullPath);
}
}
});
But I decided that I want to support compression, so I need to use a fs.createReadStream()file to read, as in this example I'm looking at:
var acceptEncoding = req.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}
var raw = fs.createReadStream(fullPath);
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);
}
So, my problem is that I am trying to figure out how to include error handling in the stream, because it fs.createReadStream()does not fulfill the callback function.
How to handle errors for Node.js fs.createReadStream ()?
user2076675
source
share