how to append to a file on particular position using node.js? [closed]

I have a file and I want to append data to particular position on it.

I went through but I couldn't found to append data on specific position in file.

So any help would be appreciated.Thank you.!!



Refer this link

Using this you can write to a specific position in a file.

Code snippet:

var position = 5;
var file_path = 'file.txt';
var new_text = 'abcde';

fs.readFile(file_path, function read(err, data) {
    if (err) {
        throw err;
    var file_content = data.toString();
    file_content = file_content.substring(position);
    var file = fs.openSync(file_path,'r+');
    var bufferedText = new Buffer(new_text+file_content);
    fs.writeSync(file, bufferedText, 0, bufferedText.length, position);

The file.txt should be on the same path.

file.txt already contains this text: OldText

Output: The new text will be OldTeabcdext i.e, OldTeabcdext


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.