Node.js sporadically unable to write file with: Error: ENOENT, open 'filename'

I am working on a node.js application that accesses the file system. In my testing, I noticed something very strange that Google could not answer for me.

My code works fine in 95% of cases, but sometimes I get this error: "Error: ENOENT, open" test.Q3rax ", where test.Q3rax is randomly generating the file name. This file must be writable, and if I ran my code again, with a hard file name code, it works fine.

Here is the code in which it does not work:

npJSON.prototype._writeFile = function(newData) {
    if (!this.loaded)
        throw "ERROR: npJSON._writeFile() was called before any data was loaded.";
    var stringToWrite = JSON.stringify(newData);
    fs.writeFile(this.fileName,stringToWrite, function(err) {
        if (err)
            throw err;
    });
};

Edit: for clarification, this is how I generate random file names:

var filename = 'test.' + getRandomText(5,6);

function getRandomText(numberOfCharactersLow, numberOfCharactersHigh) {
    var numbChar = getRandomInt(numberOfCharactersLow, numberOfCharactersHigh);
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    var returnText = '';
    for (var i = 0; i < numbChar; i++) {
        returnText += possible.charAt(getRandomInt(0, 62));
    }
    return returnText;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
+3
source share
2 answers

, , Node O_SYNC . , , ​​ . ( fs.writeFile()): http://www.daveeddy.com/2013/03/26/synchronous-file-io-in-nodejs/

. , :

var fs = require('fs');
var fname = '/tmp/fs.' + process.pid + '.tmp';
var buf = new Buffer(1024);
buf.fill('a');

fs.writeFile(fname, buf, function(err) {
  console.log(err);
});

try {
  fs.readFileSync(fname);
} catch(e) {
  console.log(e.stack);
}

process.on('exit', function() {
  try { fs.unlinkSync(fname); } catch(e) {}
});

// Output:
// Error: ENOENT, no such file or directory '/tmp/fs.31281.tmp'
+3

All Articles