3

I am currently trying to write a binary file using NodeJS.

I have now the issue that I have no clue how to insert data between two bytes without overwriting the following bytes.

Example

Given: 04 42 55 43 48 04

I know want to insert 55 between 43 and 48.

Expected result: 04 42 55 43 55 48 04

Actual result: 04 42 55 43 55 04

Code

I am using the following code to write to my file:

fs.write(fd, 0x55, 4, (err) => {
    if (err) throw err;
    fs.close(fd);
});
0

1 Answer 1

1

I couldn't find any solution so I wrote it my self

function insert_data(fd, data, position, cb) {
    // ensure data i Buffer
    if (!Buffer.isBuffer(data)) {
        data = Buffer.from(data);
    }
    // get file size
    fs.fstat(fd, (err, stat) => {
        if (err) {
            return cb(err);
        }
        // calculate size for following bytes in file and allocate
        const buffer_size = stat.size > position ? stat.size - position : 0;
        const buffer = Buffer.alloc(buffer_size);
        // read bytes to by written after inserted data
        fs.read(fd, buffer, 0, buffer_size, position, (err, bytesRead, buffer) => {
            if (err) {
                return cb(err);
            }
            // concatenate new buffer containing data to be inserted and remaining bytes 
            const new_buffer = Buffer.concat([
                data,
                buffer
            ], data.length + buffer_size);
            // write new buffer starting from given position
            fs.write(fd, new_buffer, 0, new_buffer.length, position, (err) => {
                if (err) {
                    return cb(err);
                }
                fs.close(fd, cb);
            });
        });
    });
}

fs.open("test.bin", "r+", (err, fd) => {
    insert_data(fd, [0x55], 4, console.dir);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much :) Was thinking about that approach as well but didn't want to make it more complicated than needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.