writeFile no such file or directory

basickarl picture basickarl · Jan 15, 2016 · Viewed 61.2k times · Source

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'

Answer

SergeS picture SergeS · Jan 15, 2016

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.