简体   繁体   中英

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. 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). 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. 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.

Any ideas on why this error is happening and how to fix it?

It looks like you're using asychronous fs calls. Async calls do not work like that.

You can do a search for NodeJS asynchronous programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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