In node.js why i'm not getting error while trying to write the non existing file

In the below code,i'm trying to write the non existing file 'doesnotexist.text' but still i'm getting the result as success.

var fs = require('fs');
fs.writeFile('doesnotexist.text', 'Hello World!', function (err) {
if (err) {
   console.log('error is '+err);
   return;
 }
else{
  console.log('success.');
 }
});

Because the writeFile function creates the file if it does not exist.

Basically, you can change the behavior of this function by submitting an options object as third parameter, as described in the documentation. For the flags property you can provide any value from the ones described in the documentation for fs.open.

For write, they are:

  • w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  • wx - Like w but opens the file in exclusive mode.
  • w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
  • wx+ - Like w+ but opens the file in exclusive mode.

The default value for writeFile is w, hence the file is created if it does not exist. As there is no option that provides an error when the file does not exist, you need an additional check whether the file already exists.

For this, check out the fs.exists function (see documentation for details).

Basically, your code should somewhat like this:

var fs = require('fs');
fs.exists('foo.txt', function (exists) {
  if (!exists) {
    return 'Error, file foo.txt does not exist!';
  }

  fs.writeFile('foo.txt', ...);
});