N
N
Nikolai2018-07-27 15:48:55
JavaScript
Nikolai, 2018-07-27 15:48:55

How to write a string to the middle of a file in NodeJS?

Is it possible to write a line in the middle of a file without overwriting the entire file?
For example, there is a test.txt file with the content:
1234567890abcdfghijklmnoprstxyz
You need to write the string "++" instead of "ab", that is, what would happen:
1234567890++cdfghijklmnoprstxyz
I try this:

var fs = require('fs');
var path = require('path');

var fd = fs.openSync(path.join(process.cwd(), 'test.txt'), 'a+');

var buf=Buffer.from("++","utf8");

fs.writeSync(fd, buf, 0,2, 10);

console.log('closing file now')
fs.closeSync(fd);

But "++" is written to the end of the file, changing the fs.writeSync parameters does not help, it still writes a line to the end of the file. Although according to the documentation https://nodejs.org/api/fs.html#fs_fs_writesync_fd_... , there is a position parameter.
And in fs.readSync(fd, buf, 0,2,10); position works, and reads the string from the desired position.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question