Payne Chu Payne Chu - 10 months ago 43
Node.js Question

node.js how to insert string to beginning of file but not replace the original text?

The code below inserted

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)


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);


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, buffer.length, data.length); //append old data