You cannot extend the size of a Buffer
object after it has been created, but you can write data to any location in the buffer. As described in Table 5.2, there are several methods you can use when writing to buffers.
To illustrate writing to buffers, the code in Listing 5.1 defines a buffer, fills it with zeros, writes some text at the beginning using write()
at line 4, and adds some additional text that alters part of the existing buffer via write(string, offset, length)
at line 6. Then in line 8 it adds a +
to the end by directly setting the value of an index. Figure 5.1 shows the output of this code. Notice that the buf256.write("more text", 9, 9)
statement writes to the middle of the buffer, and buf256[18] = 43
changes a single byte.
1 buf256 = new Buffer(256);
2 buf256.fill(0);
3 buf256.write("add some text");
4 console.log(buf256.toString());
5 buf256.write("more text", 9, 9);
6 console.log(buf256.toString());
7 buf256[18] = 43;
8 console.log(buf256.toString());