Insert text in file at position without overriding existent characters using NodeJS

I have an empty line in my file and I know it’s position. How can I fill that line with text? Currently if I write to it it will override the “n” terminator.

Answer

It’s not truly possible to directly append to a certain position, however, it is possible to get the contents of the file and then insert it to any given position using:

const fs = require("fs");

function appendPos(path, position, data) {
    try {
        const content = fs.readFileSync(path, "utf-8");

        writeFileSync(path, content.substring(0, position) + data + content.substring(position), { encoding: "utf-8" });
    } catch (error) {
        throw error;
    }
}