Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Overwriting a file

I know it is a simple question, but haven't been able to find anything useful on this one.

How do you use fs.createWriteStream(dst) to overwrite a file? (note that the app is hosted on heroku)

I tried {flags: 'w'} or {flags: 'r+'} even {flags: 'wb'}. None of these worked, I keep getting Error: File uploads/1.txt exists.

like image 301
Michael Yagudaev Avatar asked Aug 16 '12 21:08

Michael Yagudaev


People also ask

How do I not overwrite a node js file?

To write in a text file without overwriting with Node. js, we can use the appendFile method. to call fs. appendFile with the path of the file to write to and the content to write into the file respectively.

What is writeFileSync?

writeFileSync() is a synchronous method & creates a new file if the specified file does not exist while fs. writeFile() is an asynchronous method.

How do you delete a file in node JS?

In Node. js, you can use the fs. unlink() method provided by the built-in fs module to delete a file from the local file system.


2 Answers

From the docs:

Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w.

So {flags: 'w'} should work. This sounds like a permissions issue?

Are you able to do an fs.unlink() on that file? This should test the permissions on that file if you don't have access to the computer directly.

like image 180
Gates VP Avatar answered Sep 22 '22 17:09

Gates VP


Isn't the flag 'w' set by default ? https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options

like image 20
dparkar Avatar answered Sep 20 '22 17:09

dparkar