Reputation: 25729
I have this buffer: <Buffer 0d 0a>
and I am wondering how I can replicate it so I can test against it.
With <Buffer 00>
I was able to do new Buffer([00])
but when I do new Buffer([0d 0a])
or new Buffer([0d, 0a])
I get an error.
_0d0a = new Buffer([0d 0a]);
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Any help?
Update:
I need to create the buffer and not copy it as a stream I'm listening to sends the buffer I am looking for.
Upvotes: 1
Views: 1351
Reputation: 2556
Those bytes are shown as numbers in hexadecimal. To enter them into JavaScript, you need to prefix them with 0x
:
var CRLF = new Buffer([0x0d, 0x0a]);
Alternatively you can create a buffer from a string of hex:
var CRLF = new Buffer('0d0a', 'hex');
Note that this will throw an error (“TypeError: Invalid hex string”) if the string contains spaces or other characters, but you can remove those first:
var CRLF = new Buffer('0d 0a'.replace(/\W/g, ''), 'hex');
Upvotes: 5
Reputation: 1159
By the API docs at http://nodejs.org/api/buffer.html, the most straightforward seems to be:
var copy = new Buffer(existing.length);
existing.copy(copy)
The copy
will be a Buffer containing the copy of the contents of the Buffer existing
.
Upvotes: 1
Reputation: 3793
I'm not sure if this is considered the 'canonical' way, but it works:
buff1 = new Buffer("hi there!");
buff2 = new Buffer(buff1.length);
buff1.copy(buff2);
console.log(buff2.toString()); // hi there!
Upvotes: 1