2014-09-19 27 views
1

我是新來的節點JS和我試圖做到以下幾點:文件之前刪除其使用節點JS

function createPasswordfile(content) 
{ 
    fs.writeFile(passwordFileName,content, function(err) { 
     if(err) { 
      console.log("Failed on creating the file " + err) 
     } 
    }); 

    fs.chmodSync(passwordFileName, '400'); 
} 

function deletePasswordFile() 
{ 
    fs.chmodSync(passwordFileName, '777'); 
    fs.unlink(passwordFileName,function (err) { 
     if (err) throw err; 
     console.log('successfully deleted'); 
    }); 
} 

有三個報表時調用這些函數:

createPasswordfile(password) 
someOtherFunction() //which needs the created password file 
deletePasswordFile() 

我現在面臨的問題是,當我加入deletePasswordFile()方法調用,我得到的錯誤是這樣的:

Failed on creating the file Error: EACCES, open 'password.txt' 
successfully deleted 

由於它的非阻塞性,我猜deletePasswordFile函數會在其他函數使用它之前刪除文件。如果deletePasswordFile被註釋掉,事情工作正常。

我應該如何預防?

回答

1

writeFile是異步的,所以當您嘗試刪除文件時,文件仍然有可能被寫入。

嘗試更改爲writeFileSync

fs.writeFileSync(passwordFileName, content); 
+0

現在,我得到的錯誤'類型錯誤:錯誤的參數 在Object.fs.writeFileSync(fs.js:960:11)' – batman 2014-09-19 10:45:45

+0

@batman對不起,它並不需要回調函數:) – Jivings 2014-09-19 10:48:15

+0

感謝它工作。真的很難調試你習慣的異步代碼 – batman 2014-09-19 10:49:30