Skip to content

Commit 7602b1c

Browse files
committed
add content for buffers
1 parent d4b0abf commit 7602b1c

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

buffers-and-streams/buffers.md

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,55 @@ url: buffers
66

77
## Buffers
88

9-
### Usage
9+
Node's `Buffer` class enables working with binary data in Javascript. A buffer is allows a programme to store data temporarily outside the V8 engine's stack.
10+
11+
Though not entirely accurate we can think of a buffer as an array of bytes, each byte is represented by a hexadecimal digit.
1012

1113
The Node `Buffer` class is a global class and therefore does not need to be imported into a module.
14+
15+
### A simple example
16+
17+
```javascript
18+
// create a buffer from a string
19+
const myBuffer = Buffer.from("hello node buffers");
20+
21+
console.log(myBuffer);
22+
// <Buffer 68 65 6c 6c 6f 20 6e 6f 64 65 20 62 75 66 66 65 72 73>
23+
24+
console.log(myBuffer[0]);
25+
// 104 - unicode char code for h (decimal representation of hex number 68)
26+
27+
console.log(myBuffer.toString());
28+
// hello node buffers
29+
```
30+
31+
## Instantiating a Buffer
32+
33+
Buffers can be instantiated with:
34+
35+
- a string
36+
- an array
37+
- another Buffer
38+
- an arrayBuffer
39+
- an object
40+
41+
using `Buffer.from()`.
42+
43+
Buffers can also be instantiated by size using `Buffer.alloc()`, `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`
44+
45+
> _Unsafe_ as the memory containing the buffer is not initialised - i.e. not zeroed-out, so the potential exists for sensitive data to be leaked.
46+
47+
```
48+
const myBuffer1 = Buffer.from([1, 2, 3]);
49+
console.log(myBuffer1.length);
50+
// 3
51+
52+
const myBuffer2 = Buffer.alloc(3);
53+
console.log(myBuffer2);
54+
// <Buffer 00 00 00>
55+
56+
// allocate a size for the buffer and give each byte an initial value 'a'
57+
const myBuffer3 = Buffer.alloc(3, 'a');
58+
console.log(myBuffer3);
59+
// <Buffer 61 61 61>
60+
```

0 commit comments

Comments
 (0)