patternjavascriptMinor
Checking if a file exists then do something if it's not a directory
Viewed 0 times
directoryfilecheckingthenexistsnotsomething
Problem
While I'm aware that code with callbacks tends to be complex, I'm wondering if there are any patterns or something to improve my situation.
All I do here is check if a file exists and then print its name if it's not a directory:
All I do here is check if a file exists and then print its name if it's not a directory:
var fs = require('fs'),
filename = process.args[2];
fs.exists(filename, function(exists) {
if (exists) {
fs.stat(filename, function(err, stats) {
if (stats.isDirectory()) {
console.log(filename + ": is a directory");
} else {
// do something with file
console.log(filename);
}
});
} else {
console.log(filename + ": no such file");
}
});Solution
You can actually omit
And so:
So essentially, we reduced the number of indents caused by callbacks and also reduced it by restructuring
fs.exists(). The fs.stat() will return an error when the item you are testing is not there. You can scavenge through the err object that fs.stat() returns to see what error caused it. As I remember, when fs.stat() stats a non-existing entry, it returns an ENOENT, no such file or directory error.And so:
var fs = require('fs')
, filename = process.args[2]
;
fs.stat(filename, function(err, stats) {
if(err){
//doing what I call "early return" pattern or basically "blacklisting"
//we stop errors at this block and prevent further execution of code
//in here, do something like check what error was returned
switch(err.code){
case 'ENOENT':
console.log(filename + ' does not exist');
break;
...
}
//of course you should not proceed so you should return
return;
}
//back there, we handled the error and blocked execution
//beyond this line, we assume there's no error and proceed
if (stats.isDirectory()) {
console.log(filename + ": is a directory");
} else {
console.log(filename);
}
});So essentially, we reduced the number of indents caused by callbacks and also reduced it by restructuring
if-else statementsCode Snippets
var fs = require('fs')
, filename = process.args[2]
;
fs.stat(filename, function(err, stats) {
if(err){
//doing what I call "early return" pattern or basically "blacklisting"
//we stop errors at this block and prevent further execution of code
//in here, do something like check what error was returned
switch(err.code){
case 'ENOENT':
console.log(filename + ' does not exist');
break;
...
}
//of course you should not proceed so you should return
return;
}
//back there, we handled the error and blocked execution
//beyond this line, we assume there's no error and proceed
if (stats.isDirectory()) {
console.log(filename + ": is a directory");
} else {
console.log(filename);
}
});Context
StackExchange Code Review Q#20674, answer score: 7
Revisions (0)
No revisions yet.