我想知道什麼是確保路徑中的所有文件夾存在之前寫入新文件的正確方法。如何確保所有目錄之前存在使用node.js fs.writeFile
在下面的示例中,代碼失敗,因爲文件夾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() : '';
});
}
});
謝謝!
你應該刪除切片。它會跳過上一個文件夾,因爲您正在處理之前的值。即使沒有切片,它也不會到達文件,因爲它是最後一個當前文件,並且永遠不會成爲prev。 – Jompis 2016-02-15 14:13:51