writeFile no such file or directory

I have a file(data.file an image), I would like to save this image. Now an image with the same name could exist before it. I would like to overwrite if so or create it if it does not exist since before. I read that the flag "w" should do this.

Code:

fs.writeFile('/avatar/myFile.png', data.file, {
  flag: "w"
}, function(err) {
  if (err) {
    return console.log(err);
  }
  console.log("The file was saved!");
});

Error:

[Error: ENOENT: no such file or directory, open '/avatar/myFile.png']
errno: -2,
  code: 'ENOENT',
    syscall: 'open',
      path: '/avatar/myFile.png'

Solution 1:

This is probably because you are trying to write to root of file system instead of your app directory '/avatar/myFile.png' -> __dirname + '/avatar/myFile.png' should do the trick, also check if folder exists. node.js won't create parent folder for you.

Solution 2:

Many of us are getting this error because parent path does not exist. E.g. you have /tmp directory available but there is no folder "foo" and you are writing to /tmp/foo/bar.txt.

To solve this, you can use mkdirp - adapted from How to write file if parent folder doesn't exist?

Option A) Using Callbacks

const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirName = require('path').dirname;

function writeFile(path, contents, cb) {
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err);

    fs.writeFile(path, contents, cb);
  });
}

Option B) Using Async/Await

Or if you have an environment where you can use async/await:

const mkdirp = require('mkdirp');
const fs = require('fs');

const writeFile = async (path, content) => {
  await mkdirp(path);
  fs.writeFileSync(path, content);
}

Solution 3:

I solved a similar problem where I was trying to create a file with a name that contained characters that are not allowed. Watch out for that as well because it gives the same error message.

Solution 4:

I ran into this error when creating some nested folders asynchronously right before creating the files. The destination folders wouldn't always be created before promises to write the files started. I solved this by using mkdirSync instead of 'mkdir' in order to create the folders synchronously.

try {
    fs.mkdirSync(DestinationFolder, { recursive: true } );
} catch (e) {
    console.log('Cannot create folder ', e);
}
fs.writeFile(path.join(DestinationFolder, fileName), 'File Content Here', (err) => {
    if (err) throw err;
});