There are several methods for reading from buffers. The simplest is to use the toString()
method to convert all or part of a buffer to a string. However, you can also access specific indexes in the buffer directly or by using read()
. Also, Node.js provides a StringDecoder
object that has a write(buffer)
method that decodes and writes buffered data using the specified encoding. Table 5.3 describes these methods for reading Buffer
objects.
To illustrate reading from buffers, the code in Listing 5.2 defines a buffer with UTF8
encoded characters and then uses toString()
without parameters to read all the buffer and then with the encoding
, start
, and end
parameters to read part of the buffer. Then in lines 4 and 5, it creates StringDecoder
with UTF8
encoding and uses it to write the contents of the buffer out to the console. Next, a direct access method gets the value of the octet at index 18, and then on line 8, readUInt32BE()
reads a 32-bit integer. Figure 5.2 shows the output of the code in Listing 5.2.
1 bufUTF8 = new Buffer("Some UTF8 Text u00b6 u30c6 u20ac", 'utf8'),
2 console.log(bufUTF8.toString());
3 console.log(bufUTF8.toString('utf8', 5, 9));
4 var StringDecoder = require('string_decoder').StringDecoder;
5 var decoder = new StringDecoder('utf8'),
6 console.log(decoder.write(bufUTF8));
7 console.log(bufUTF8[18].toString(16));
8 console.log(bufUTF8.readUInt32BE(18).toString(16));