James James - 2 months ago 11
Node.js Question

Why does node mkdirSync() throw exception?

I am running node v4.2.0 on Windows 8. I have found that fs.mkdirSync() occasionally throws EPERM for no apparent reason.

I managed to recreate it with this test code, which I save in a file bug.js.

var fs = require("fs");
var i;
for (i = 0; i < 100000; i += 1) {
fs.mkdirSync("xx");
fs.rmdirSync("xx");
}


This is the trace I occasionally get:

C:\WIP>node bug
C:\WIP\bug.js:0

Error: EPERM: operation not permitted, mkdir 'C:\WIP\xx'
at Error (native)
at Object.fs.mkdirSync (fs.js:799:18)
at Object.<anonymous> (C:\WIP\bug.js:4:8)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3


It does not happen always, even with the 100000 loop. In fact its a slippery beast - if I run bug.js several times it seems to reduce the probability of hitting the exception. When I tried catching the exception I found that it was happening after many thousands of successful iterations of the loop.

Why does the exception occur? Is there any way to avoid the exception?

Answer

I think this is a shortcoming of the windows system, you're probably just doing actions on a folder too fast and they start to overlap and throw those errors. Have you tried this on a linux system?

It is however very much likely to get a permission denied exception, if someone were to manually change the permissions. You should always put those kind of actions in a try{}catch{} block.

EDIT:

rquist@rquist-ThinkPad-T530 ~/projects $ vim app.js # Made your code here
rquist@rquist-ThinkPad-T530 ~/projects $ node app.js 
rquist@rquist-ThinkPad-T530 ~/projects $ node app.js 
rquist@rquist-ThinkPad-T530 ~/projects $ node app.js 
rquist@rquist-ThinkPad-T530 ~/projects $ node app.js 
rquist@rquist-ThinkPad-T530 ~/projects $ node app.js 
rquist@rquist-ThinkPad-T530 ~/projects $ 

Not getting any exceptions here on Ubuntu 15.04

Comments