0

In Node.js, I noticed that file operations were not always stable. I have the impression that fs gives up when the operations are not completely finished. Here is an example to illustrate:

"use strict";

Error.stackTraceLimit = Infinity;

const fs = require("fs");
const filename = "foo.txt";

for (let i = 0; ; i++) {
    try {
        fs.writeFileSync(filename, "bar");
        fs.unlinkSync(filename);
    }
    catch (e) {
        throw Object.assign(new Error(`Error at iteration ${i}!`), { cause: e });
    }
}

After a certain number of iterations, I get an error :

Error: Error at iteration 12980!
    at Object.<anonymous> (C:\test.js:15:4)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47 {
  cause: Error: EPERM: operation not permitted, open 'foo.txt'
      at Object.openSync (fs.js:462:3)
      at Object.writeFileSync (fs.js:1384:35)
      at Object.<anonymous> (C:\test.js:10:6)
      at Module._compile (internal/modules/cjs/loader.js:999:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
      at Module.load (internal/modules/cjs/loader.js:863:32)
      at Function.Module._load (internal/modules/cjs/loader.js:708:14)
      at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
      at internal/main/run_main_module.js:17:47 {
    errno: -4048,
    syscall: 'open',
    code: 'EPERM',
    path: 'foo.txt'
  }
}
  • Do you have the same observation?
  • How can we ensure that these operations are stable?
user3515941
  • 141
  • 1
  • 8
  • Despite the error you got I strongly recommend to use `writeFile` from `fs/promises` – Anatoly Jul 02 '22 at 10:28
  • This is likely specific to an OS or filesystem (looks like you're using Windows?), and it may be beyond Node.js's control. I can't reproduce it on macOS (I stopped the program after 200.000 iterations), but UNIX filesystems typically don't care about files already being opened. – robertklep Jul 02 '22 at 10:28
  • Yes I am on Windows 7 ^^' – user3515941 Jul 02 '22 at 17:26
  • Try providing path more carefully: `require("path").resolve(__dirname, "foo.txt")` – Parzh from Ukraine Jul 02 '22 at 17:31

0 Answers0