1

I know from here that the official position is to not check for existence before manipulating a file: Node.js check exist file Rather, one should simply attempt the write and handle whatever exceptions may be thrown.

However, my scenario is that I want to only write a certain file to a folder given that the file does not already exist. If the file exists, I want to do nothing.

What would be the idiomatic way to accomplish this?

Community
  • 1
  • 1
Henrik
  • 362
  • 3
  • 10
  • Use the `fs.stat` as described in an answer to the question you linked. – Amadan Aug 28 '15 at 08:13
  • Alright. Is `fs.stat` guaranteed to return an error _only_ when the file doesn't exist? – Henrik Aug 28 '15 at 21:08
  • No. But it is guaranteed to return the specific error `'ENOENT'` (error: no entry) *only* when the file doesn't exist. Again, see FÔx Gênki's answer on the linked question. – Amadan Aug 31 '15 at 00:38
  • Right, I didn't notice that detail. Thank you! Although I must say that semantically, this is atrocious. I will pretty much have to wrap it in my own sanely named function for it to make any kind of sense to someone reading the code. – Henrik Aug 31 '15 at 22:34

2 Answers2

5

Just use fs.exists.

fs.exists('/path/to.file', function (exists) {
  if (!exists) {
    // do something
  }
});
Daniel Perez
  • 6,335
  • 4
  • 24
  • 28
3

You can try:

fs = require('fs');
fs.stat('path-to-your-file', function(err) {  
    if (err) {
       // file does not exist
    } else {
        // file exists
    }
});
biancamihai
  • 961
  • 6
  • 14
  • Am I guaranteed to get an error _only_ in the case I am looking for—that the file doesn't exist? Or might I get false negatives? – Henrik Aug 28 '15 at 21:12