Buffer is introduced

Why Buffer?

  1. Before The advent of Node/ES6, front-end engineers only needed to perform simple string or ODM operations to meet business requirements, so they were unfamiliar with binary data.
  2. After the emergence of Node, the technical scene facing front-end engineers has changed, and can be in-depth into the fields of network transmission, file manipulation, image processing and so on. These operations are closely related to binary data.
  3. A Buffer is a binary data container, similar to an array, used to store data in a Node.

The new Buffer

Buffer.alloc(size[, fil[,encoding]]) size: expected length of the new Buffer Fill is used to prefill the value of the new Buffer default 0 encoding: encoding format Default: UTF-8

/* Hexadecimal: 00-ff Decimal: 0-255 Binary: 00000000-11111111 0/1 indicates one bit. == bit 8bit = 1B 1 KB = 1024 B 1 MKB = 1024 KB 1 gb = 1024m 1TB = 1024 gb */ / 2. Buffer.alloc(size[, fill[, encoding]]) /* Class arrays can be initialized using traversable, optional subscripts, etc. : the specified length cannot change the fill value */letbuffer2= Buffer.alloc(10); // Create a buffer of length 10 buffer2[0]= 10; // You can use buffer buffer2[1]= oxfc as an array; // Pass a hexadecimal to take the last two digitsfcbuffer2[30]= 1; // This is different from array overflow hide console.log(buffer2);Copy the code

Buffer using

** Use Buffer ** using the new method

  1. Buffer.form(STR): Converts a string to a Buffer
  2. Buffer.alloc(size): Creates a Buffer of the specified size
  3. Buffer.allounsafe (size): Creates a Buffer of a specified size that may contain sensitive data.
// Historical method //letbuffer = new Buffer(10); // console.log(buffer)// < buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00> //1. The string is converted to binarylet str= 'www.zhangningle.top';
letbuffer= Buffer.from(str); console.log(buffer); //<Buffer 77 77 77 2e 7a 68 61 6E 67 6E 69 6E 67 6c 65 2e 74 6f 70 Console.log (buffer.tostring ())//www.zhangningle.top // A Chinese character is represented by three bytes after it is converted to binaryCopy the code

Summary points of Buffer:

  1. Buffers are structured like arrays and operate like arrays.
  2. Buffers store data in binary form
  3. A Buffer comes with Node and can be used directly without importing it.