How to ensure all directories exist before to fs.writeFile using node.js -
i'm wondering proper way ensure folder in path exist before write new file.
in next example, code fails because folder cache
doesn't exists.
fs.writefile(__config.path.base + '.tmp/cache/shared.cache', new date().gettime(), function(err) { if (err){ consoledev('unable write new cache timestamp in ' + __filename + ' @ ' + __line, 'error'); }else{ consoledev('cache process done!'); } callback ? callback() : ''; });
solution:
// ensure path exists mkdirp, if doesn't, create missing folders. mkdirp(path.resolve(__config.path.base, path.dirname(__config.cache.lastcachetimestampfile)), function(err){ if (err){ consoledev('unable create directories "' + __config.path.base + '" in' + __filename + ' @ ' + __line + '\n' + err.message, 'error'); }else{ fs.writefile(__config.path.base + filename, new date().gettime(), function(err) { if (err){ consoledev('unable write new cache timestamp in ' + __filename + ' @ ' + __line + '\n' + err.message, 'error'); }else{ consoledev('cache process done!'); } callback ? callback() : ''; }); } });
thanks!
use mkdirp.
if want (recursively):
var pathtofile = 'the/file/sits/in/this/dir/myfile.txt'; pathtofile.split('/').slice(0,-1).reduce(function(prev, curr, i) { if(fs.existssync(prev) === false) { fs.mkdirsync(prev); } homecoming prev + '/' + curr; });
you need piece omit file itself.
node.js fs
No comments:
Post a Comment