Created
August 22, 2012 20:23
-
-
Save Jimbly/3429037 to your computer and use it in GitHub Desktop.
fs.exists is important
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
var getSetting; | |
if ("we can use exists") { | |
getSetting = function(fn, cb) { | |
(fs.exists || path.exists)(fn, function(exists) { | |
if (!exists) { | |
return cb(undefined, 'default value'); | |
} | |
fs.readFile(fn, 'utf8', cb); | |
}); | |
}; | |
} else { | |
getSetting = function(fn, cb) { | |
fs.readFile(fn, 'utf8', function(err, data) { | |
if (err.code === 'ENOENT') { | |
return cb(undefined, 'default value'); | |
} | |
cb(err, data); | |
}); | |
}; | |
} | |
getSetting('setting.txt', function(err, value) { | |
if (err) { | |
console.warn(err); | |
} else { | |
console.log('value="' + value + '"'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment