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'
The fs. writeFileSync() creates a new file if the specified file does not exist.
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 )
fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With