how to add a first line to a text file in node.js (using fs)
Problem
I'm trying to add a first line to an existing text file using node.js.
My actual code looks as follows: var fs = require('fs');
fs.appendFile('test.txt', 'X Y', function (err) {
});
The text: 'X Y' is not added as first line, but last.
It would help a lot, if you have an idea, how to add my line as first of the document! :-)
Greetings, JS
Solution
You can't. The file systems are not designed that way. You have to write your line first to a temp file and then append the content of you file. Then rename/move your temp file to the name of the original one. (And be sure there was no error when writing, otherwise you loose the content of the original file.)
Discussion
View additional discussion.