Slicing Buffers

Another important aspect of working with buffers is the ability to divide them into slices. A slice is a section of a buffer between a starting index and an ending index. Slicing a buffer allows you to manipulate a specific chunk.

You create slices by using slice([start], [end]), which returns a Buffer object that points to the start index of the original buffer and has a length of end – start. Keep in mind that a slice is different from a copy. If you edit a copy, the original does not change. However, if you edit a slice, the original does change.

The code in Listing 5.4 illustrates using slices. The important thing to note is that when the slice is altered in lines 5 and 6, it also alters the original buffer, as shown in Figure 5.4.

Listing 5.4 buffer_slice.js: Creating and manipulating slices of a Buffer object


1 var numbers = new Buffer("123456789");
2 console.log(numbers.toString());
3 var slice = numbers.slice(3, 6);
4 console.log(slice.toString());
5 slice[0] = '#'.charCodeAt(0);
6 slice[slice.length-1] = '#'.charCodeAt(0);
7 console.log(slice.toString());
8 console.log(numbers.toString());


Image

Figure 5.4 Output of buffer_slice.js, slicing and modifying a Buffer object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.196.241