2014-10-11 28 views
3

我想知道什麼是確保路徑中的所有文件夾存在之前寫入新文件的正確方法。如何確保所有目錄之前存在使用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() : ''; 
      }); 
     } 
    }); 

謝謝!

回答

3

使用mkdirp

如果你真的想自己做(遞歸):

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); 
    } 
    return prev + '/' + curr; 
}); 

您需要切片省略文件本身。

+2

你應該刪除切片。它會跳過上一個文件夾,因爲您正在處理之前的值。即使沒有切片,它也不會到達文件,因爲它是最後一個當前文件,並且永遠不會成爲prev。 – Jompis 2016-02-15 14:13:51

2

您可以使用fs.existsSync來檢查,如果你的目錄存在,如果不創建它:

if (fs.existsSync(pathToFolder)===false) { 
    fs.mkdirSync(pathToFolder,0777); 
} 
+0

這會給不存在路徑的各個層面?另外,爲什麼要將同步代碼引入異步操作? – jfriend00 2014-10-11 18:44:02

+0

@ jfriend00不,它不會。也許[mkdirp](https://www.npmjs.org/package/mkdirp)。 – hobbs 2014-10-11 18:49:13

+0

同步會阻止您的寫入文件在創建文件夾之前運行。 @hobbs mkdirp是一個不錯的選擇。 – xShirase 2014-10-11 18:53:15

2

fs-extra有一個功能,我發現這樣做很有用。

的代碼會是這樣的:

var fs = require('fs-extra'); 

fs.ensureFile(path, function(err) { 
    if (!err) { 
    fs.writeFile(path, ...); 
    } 
}); 
+0

確實有用! :) – Vadorequest 2016-02-09 20:34:04

相關問題