filesystems - node.js how to insert string to beginning of file but not replace the original text? -
the code below inserted somestring
file replace text inside 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 file in append mode using a+
flag
var fd = fs.opensync('file', 'a+');
or use positional write
. able append end of file, use fs.appendfile
:
fs.appendfile(fd, buf, err => { // });
write beginning of file:
fs.write(fd, buf, 0, buf.length, 0);
edit:
i guess there isn't single method call that. can copy contents of file, write new data, , append copied data.
var data = fs.readfilesync(file); //read existing contents data var fd = fs.opensync(file, 'w+'); var buffer = new buffer('new text'); fs.writesync(fd, buffer, 0, buffer.length, 0); //write new data fs.writesync(fd, data, 0, data.length, buffer.length); //append old data // or fs.appendfile(fd, data); fs.close(fd);
please note must use asynchronous versions of these methods if these operations aren't performed once during initialization, they'll block event loop.
Comments
Post a Comment