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.
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.
writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.
nodejs's fs. rename() overwrites files because that is how the Unix rename() is defined and fs.
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.
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') });
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