【发布时间】:2016-02-10 02:11:07
【问题描述】:
我想知道在写入新文件之前确保路径中的所有文件夹都存在的正确方法是什么。
在以下示例中,代码失败,因为文件夹 cache 不存在。
fs.writeFile(__config.path.base + '.tmp/cache/shared.cache', new Date().getTime(), function(err) {
if (err){
consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line, 'error');
}else{
consoleDev('Cache process done!');
}
callback ? callback() : '';
});
解决方案:
// Ensure the path exists with mkdirp, if it doesn't, create all missing folders.
mkdirp(path.resolve(__config.path.base, path.dirname(__config.cache.lastCacheTimestampFile)), function(err){
if (err){
consoleDev('Unable to create the directories "' + __config.path.base + '" in' + __filename + ' at ' + __line + '\n' + err.message, 'error');
}else{
fs.writeFile(__config.path.base + filename, new Date().getTime(), function(err) {
if (err){
consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line + '\n' + err.message, 'error');
}else{
consoleDev('Cache process done!');
}
callback ? callback() : '';
});
}
});
谢谢!
【问题讨论】: