[Nodejs] Something about Buffer

Written by peterchang_82818 | Published 2017/10/02
Tech Story Tags: javascript | nodejs | react | buffer

TLDRvia the TL;DR App

In node.js a buffer is a container for raw bytes. A byte just means eight bits, and a bit is just a 0 or a 1. So a byte might look like 10101010 (From Allen).

1- What does a Buffer look like?

Basically buffer could be appeared in two main forms

const Buffer = require('buffer').Buffer;const buf = Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64]);

Form 1, raw memory chunk

console.log(buf);// outputs <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>

Form 2, decode format (could be utf16le, utf8 etc. [_more_](https://www.tutorialspoint.com/nodejs/nodejs_buffers.htm))

console.log(buf.toString('utf16le'));// outputs '敨汬潷汲'console.log(buf.toString('utf8'));// outputs 'hello world'

2- Creating Buffers

This is the part taken the note from Josh. There are a few ways to create new buffers:

Uninitiated Buffer of n octets

var buffer = new Buffer(8);

Buffer from a given array

This buffer is uninitialized and contains 8 bytes.

var buffer = new Buffer([ 8, 6, 7, 5, 3, 0, 9]);

Buffer from a given string.

This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes.

var buffer = new Buffer("I'm a string!", "utf-8")

3- Operation

More Fun With Buffers

  • Writing to Buffers
  • Reading from Buffers buf.toString(‘utf8’,0,5)
  • Convert Buffer to JSON var json = buf.toJSON(buf);
  • Concatenate Buffers var buffer3 = Buffer.concat([buffer1,buffer2]);
  • Compare Buffers buf.compare(otherBuffer);
  • Copy Buffer buffer1.copy(buffer2);
  • Slice Buffer var buffer2 = buffer1.slice(0,9);
  • Buffer Length buffer.length

Reference:

https://nodejs.org/docs/latest/api/buffer.html#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe

https://docs.nodejitsu.com/articles/advanced/buffers/how-to-use-buffers/

https://allenkim67.github.io/programming/2016/05/17/nodejs-buffer-tutorial.html

https://www.tutorialspoint.com/nodejs/nodejs_buffers.htm

https://flink.apache.org/news/2015/05/11/Juggling-with-Bits-and-Bytes.html


Published by HackerNoon on 2017/10/02