SSpoke
SSpoke

Reputation: 5836

remove elements from front of Buffer node.js

I know there is a function called slice() but I am looking for splice() and that function doesn't exist how would I go about doing it some other way?

var buffer = new Buffer("090001060001020304090000060001020304", "hex");
var packetLength = buffer.readUInt16LE(0)
console.log('before slice buffer = ' + buffer.toString('hex'))
buffer = buffer.slice(0, packetLength)
console.log('after slice buffer = ' + buffer.toString('hex'))

the output I get is

before slice buffer = 090001060001020304090000060001020304
after slice buffer = 090001060001020304

But i need to get

before slice buffer = 090001060001020304090000060001020304
after slice buffer = 090000060001020304

the front 9 bytes should get removed and the bytes after it should be moved to the front how do I do this easy way?

Upvotes: 2

Views: 5216

Answers (2)

peteb
peteb

Reputation: 19428

Just change the starting point of your buffer to be offset by 9 instead of starting from 0

let newBuffer = buffer.slice(9).toString('hex')

Upvotes: 3

SSpoke
SSpoke

Reputation: 5836

Solved it..

console.log('before slice buffer = ' + buffer.toString('hex'))
var newBuffer = new Buffer(buffer.length - packetLength);
buffer.copy(newBuffer, 0, packetLength, packetLength + buffer.length);
console.log('after slice buffer =  ' + newBuffer.toString('hex'))


before slice buffer = 090001060001020304090000060001020304
after slice buffer =  090000060001020304

Upvotes: 0

Related Questions