Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 15651  / 10 Years ago, wed, december 24, 2014, 12:00:00

I built a simple server that handled errors (files that aren't found, for example) which works fine:



    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);
}
}
});


But I decided that I want to support compression, so I need to use fs.createReadStream() to read the file, like in this example that I'm looking at:



//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(/bdeflateb/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/bgzipb/)) {
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'm trying to figure out how to incorporate my error handling into the stream approach since fs.createReadStream() doesn't take a callback function.



How do I handle errors for Node.js fs.createReadStream()?


More From » node.js

 Answers
6

Streams can emit an error event. You can listen for this event to prevent the default behavior of throwing the error:



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

[#68392] Monday, December 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lewis

Total Points: 739
Total Questions: 100
Total Answers: 94

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;