简体   繁体   English

EPERM 阻止的文件写入权限 - 删除然后写入新文件。 Node.js

[英]File writing permissions blocked by the EPERM - Deleting then writing a new file. Node.js

I have a file system function which deletes a file then creates a new one with all new data, I am looking for a possible fix for an error that occurs randomly, and not every time, but around every other time.我有一个文件系统 function 删除一个文件,然后使用所有新数据创建一个新文件,我正在寻找一种可能的解决方案来解决随机发生的错误,而不是每次发生,而是每隔一段时间发生一次。 Here is my current code:这是我当前的代码:

try {
   if(fs.existsSync(file)) {
      fs.unlink(file, function (err) {}); 
   }
} catch (error){
   console.log('There was no file to be deleted');
}
fs.open(file, 'w', function (err, file) {
   if (err) throw err;
});
var logger = fs.createWriteStream(file, {
    flags: 'a' // 'a' means appending (old data will be preserved)
});

which throws the error occasionally:偶尔会引发错误:

C:\Users\codel\OneDrive\Documents\BattlEye\index.js:265
        if (err) throw err;
                 ^

Error: EPERM: operation not permitted, open 'C:\Users\codel\OneDrive\Documents\BattlEye\files\610636905440215071.txt'
Emitted 'error' event on WriteStream instance at:
    at internal/fs/streams.js:375:14
    at FSReqCallback.oncomplete (fs.js:171:23) {
  errno: -4048,
  code: 'EPERM',
  syscall: 'open',
  path: 'C:\\Users\\codel\\OneDrive\\Documents\\BattlEye\\files\\610636905440215071.txt'
}

First thing that is noticeable is that this is a cloud drive(OneDrive).首先值得注意的是,这是一个云驱动器(OneDrive)。 With my lack of knowledge about permissions, I decided to test out if the problem was in the OneDrive by transferrring the file to my harddrive.由于我对权限缺乏了解,我决定通过将文件传输到我的硬盘驱动器来测试问题是否出在 OneDrive 中。 The results were not surprising.结果并不令人惊讶。 It didn't change a thing.它没有改变任何事情。

C:\Users\codel\Documents\BattlEye\index.js:265
        if (err) throw err;
                 ^

[Error: EPERM: operation not permitted, open 'C:\Users\codel\Documents\BattlEye\files\610636905440215071.txt'] {
  errno: -4048,
  code: 'EPERM',
  syscall: 'open',
  path: 'C:\\Users\\codel\\Documents\\BattlEye\\files\\610636905440215071.txt'
}

But the Emmitted 'error' event on WriteStream disappeared from the error log.但是 WriteStream 上的 Emmitted 'error' 事件从错误日志中消失了。

Any ideas on why this error is happening and how to fix it?关于为什么会发生此错误以及如何解决此错误的任何想法?

It looks like you're using asychronous fs calls.看起来您正在使用异步 fs 调用。 Async calls do not work like that.异步调用不是这样工作的。

You can do a search for NodeJS asynchronous programming.您可以搜索 NodeJS 异步编程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM