title: Creating a file only if it doesn't exist in Node.js
body: <p>We have a buffer we'd like to write to a file. If the file already exists, we need to increment an index on it, and try again. Is there a way to create a file only if it doesn't exist, or should I just stat files until I get an error to find one that doesn't exist already?</p>
  
  <p>For example, I have files <code>a_1.jpg</code> and <code>a_2.jpg</code>. I'd like my method to try creating <code>a_1.jpg</code> and <code>a_2.jpg</code>, and fail, and finally successfully create <code>a_3.jpg</code>.</p>
  
  <p>The ideal method would look something like this:</p>
  
  <pre><code>fs.writeFile(path, data, { overwrite: false }, function (err) {
    if (err) throw err;
    console.log('It\'s saved!');
  });
  </code></pre>
  
  <p>or like this:</p>
  
  <pre><code>fs.createWriteStream(path, { overwrite: false });
  </code></pre>
  
  <p>Does anything like this exist in node's <code>fs</code> library?</p>
  
  <p><em>EDIT</em>: My question isn't if there's a separate function that checks for existence. It's this: is there a way to create a file if it doesn't exist, in a single file system call?</p>