The code below inserted somestring to file but also will replace the text inside the file. how can fix this?
fd = fs.openSync('file', 'r+')
buf = new Buffer('somestring')
fs.writeSync(fd, buf, 0, buf.length, 0)
fs.close(fd)
Open the file in append mode using the a+ flag
var fd = fs.openSync('file', 'a+');
Or use a positional write. To be able to append to end of file, you need the size of the file.
var stats = fs.statSync('file');
fs.write(fd, buf, 0, buf.length, stats.size);
Write to the beginning of a file:
fs.write(fd, buf, 0, buf.length, 0);
EDIT:
I guess there isn't a single method call to that. But you can copy the contents of the file, write new data, and append the copied data.
var data = fs.readFileSync(file); //read existing contents into data
var fd = fs.openSync(file, 'w+');
var buffer = new Buffer('New text');
fs.writeSync(fd, buffer, 0, buffer.length); //write new data
fs.writeSync(fd, data, 0, data.length); //append old data
fs.close(fd);