在节点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
被注释掉,事情工作正常。
我应该如何防止呢?
writeFile
是asynchronous的,因此当您尝试删除文件时,文件仍然可能正在写入。
尝试更改为writeFileSync
。
fs.writeFileSync(passwordFileName, content);