Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write in a text file without overwriting in fs node js

Tags:

How I can add text in my file but without overwriting the old text. I use the module fs (node js)

I tried this code but it doesn't work.

fs.writeFileSync("file.txt", 'Text', "UTF-8",{'flags': 'w+'}); 

any suggestion and Thanks.

like image 449
dardar.moh Avatar asked Jun 26 '13 15:06

dardar.moh


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.

Does fs write file overwrite?

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

Does fs rename overwrite?

nodejs's fs. rename() overwrites files because that is how the Unix rename() is defined and fs.


2 Answers

Check the flags here: http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback - you are currently using w+ which:

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

You should use a instead:

'a' - Open file for appending. The file is created if it does not exist.

'ax' - Like 'a' but opens the file in exclusive mode.

'a+' - Open file for reading and appending. The file is created if it does not exist.

'ax+' - Like 'a+' but opens the file in exclusive mode.

like image 95
Prisoner Avatar answered Sep 19 '22 15:09

Prisoner


Use fs.appendFile, that will just append the new information!

fs.appendFile("file.txt", 'Text',function(err){ if(err) throw err; console.log('IS WRITTEN') }); 
like image 35
Doris Hernandez Avatar answered Sep 20 '22 15:09

Doris Hernandez