1

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?

1 Answers1

1

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.

Gerard Setho
  • 109
  • 2