Skip to content

Commit 997d771

Browse files
committed
More buffer stuff
1 parent 2f5efc6 commit 997d771

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

‎chapters/buffers.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,27 @@ The simplest way to construct a `Buffer` from a string is to simply pass a strin
1616
An alternative method is to pass an array of integers representing the octet stream, however in this case functionality equivalent.
1717

1818
var hello = new Buffer([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
19+
20+
Buffers can also be created with an integer representing the number of bytes allocated, after which we may call the `write()` method, providing an optional offset and encoding. As shown below we provide the offset of 2 bytes to our second call to `write()`, buffering "Hel", and then we continue on to write another two bytes with an offset of 3, completing "Hello".
21+
22+
var buf = new Buffer(5);
23+
buf.write('He');
24+
buf.write('l', 2);
25+
buf.write('lo', 3);
26+
console.log(buf.toString());
27+
// => "Hello"
28+
29+
The `.length` property of a buffer instance contains the byte length of the stream, compared to JavaScript strings which will simply return the number of characters. For example the ellipsis character '…' consists of three bytes, however the buffer will respond with the byte length, and not the character length.
30+
31+
var ellipsis = new Buffer('…', 'utf8');
32+
33+
console.log('… string length: %d', '…'.length);
34+
// => … string length: 1
35+
36+
console.log('… byte length: %d', ellipsis.length);
37+
// => … byte length: 3
38+
39+
console.log(ellipsis);
40+
// => <Buffer e2 80 a6>
41+
42+
When working with JavaScript strings, we can also pass a string through the `Buffer.byteLength()` method to determine it's byte length.

‎src/buffer/examples.js‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,20 @@ console.log(hello.toString());
55

66
var hello = new Buffer([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
77
console.log(hello);
8-
console.log(hello.toString());
8+
console.log(hello.toString());
9+
10+
var hello = new Buffer([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
11+
console.log(hello);
12+
console.log(hello.toString());
13+
14+
var ellipsis = new Buffer('…');
15+
console.log('… string length: %d', '…'.length);
16+
console.log('… byte length: %d', ellipsis.length);
17+
console.log('… byte length: %d', Buffer.byteLength('…'));
18+
console.log(ellipsis);
19+
20+
var buf = new Buffer(5);
21+
buf.write('he');
22+
buf.write('l', 2);
23+
buf.write('lo', 3);
24+
console.log(buf.toString());

0 commit comments

Comments
 (0)