Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writeFile no such file or directory

Tags:

node.js

fs

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' 
like image 538
basickarl Avatar asked Jan 15 '16 12:01

basickarl


People also ask

Does FS writeFile create a file?

The fs. writeFileSync() creates a new file if the specified file does not exist.

What is writeFile in node JS?

writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The 'options' parameter can be used to modify the functionality of the method. Syntax: fs.writeFile( file, data, options, callback )

Does FS writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.


1 Answers

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.

like image 94
SergeS Avatar answered Sep 17 '22 09:09

SergeS