What is Buffer in Node.js?
Buffers are instances of the Buffer
class in node, which is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.
Pure JavaScript does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, Node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both which make it necessary to deal with purely binary streams of data. Below are the ways to create new buffers:
var bufferOne = new Buffer(8);
// Uninitalized buffer and contains 8 bytes
var bufferTwo = new Buffer([ 8, 6, 7]);
//This initializes the buffer to the contents of this array. The array are integers representing bytes.
var bufferThree = new Buffer("This is a string", "utf-8")
// This initializes the buffer to a binary encoding of the first string as specified by the second argument (in this case, utf-8).
Comments
Post a Comment