Reputation: 173
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.
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
I am using the following code to write to my file:
fs.write(fd, 0x55, 4, (err) => {
if (err) throw err;
fs.close(fd);
});
Upvotes: 3
Views: 446
Reputation: 8060
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);
});
Upvotes: 1