Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  82] [ 4]  / answers: 1 / hits: 17180  / 8 Years ago, wed, february 3, 2016, 12:00:00

Im trying to write into a text file in node.js.
Im doing this the following way:



fs.writeFile(persistence\announce.txt, string, function (err) {
if (err) {
return console.log(Error writing file: + err);
}
});


whereas string is a variable.



This function will begin it`s writing always at the beginning of a file, so it will overwrite previous content.



I have a problem in the following case:



old content:



Hello Stackoverflow


new write:



Hi Stackoverflow


Now the following content will be in the file:



Hi stackoverflowlow


The new write was shorter then the previous content, so part of the old content is still persistent.



My question:



What do I need to do, so that the old content of a file will be completely removed before the new write is made?


More From » node.js

 Answers
26

You can try truncating the file first:



fs.truncate(persistence\announce.txt, 0, function() {
fs.writeFile(persistence\announce.txt, string, function (err) {
if (err) {
return console.log(Error writing file: + err);
}
});
});

[#63460] Monday, February 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
masonm

Total Points: 167
Total Questions: 87
Total Answers: 103

Location: Rwanda
Member since Wed, Jun 8, 2022
2 Years ago
masonm questions
;