Skip to main content

Node.js Buffer Explained

What are Buffers?

Binary is simply a set or a collection of 1 and 0. Each number in a binary, each 1 and 0 in a set are called a bit. Computer converts the data to this binary format to store and perform operations. For example, the following are five different binaries:

10, 01, 001, 1110, 00101011

JavaScript does not have a byte type data in its core API. To handle binary data Node.js includes a binary buffer implementation with a global module called Buffer.

Creating a Buffer

There are different ways you can create a buffer in Node.js. You can create an empty buffer by with a size of 10 bytes.

const buf1 = Buffer.alloc(10);

From UTF-8-encoded strings, the creation is like this:

const buf2 = Buffer.from('Hello World!');

There are different accepted encoding when creating a Buffer:

  • ascii
  • utf-8
  • base64:
  • latin1
  • binary
  • hex

There are three separate functions allocated in the Buffer API to use and create new buffers. In above examples we have seen alloc() and from(). The third one is allocUnsafe().

const buf3 = Buffer.allocUnsafe(10);

When returned, this function might contain old data that needs to be overwritten.

Interactions with Buffer

There are different interactions that can be made with the Buffer API. We are going to cover most of them here. Let us start with converting a buffer to JSON.

let bufferOne = Buffer.from('This is a buffer example.');
console.log(bufferOne);

// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>

let json = JSON.stringify(bufferOne);
console.log(json);

// Output: {"type": "Buffer", "data": [84,104,105,115,32,105,115,32,97,32,98,117,102,102,101,114,32,101,120,97,109,112,108,101,46]}

The JSON specifies that the type of object being transformed is a Buffer, and its data. Converting an empty buffer to JSON will show us that it contains nothing but zeros.

const emptyBuf = Buffer.alloc(10);

emptyBuf.toJSON();

// Output: { "type": "Buffer", "data": [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] }

Do notice that, Buffer API also provides a direct function toJSON() to convert a buffer into a JSON object. To examine the size of a buffer, we can use lengthmethod.

emptyBuf.length;
// Output: 10

Now let us convert buffer to a readable string, in our case, the utf-8 encoded.

console.log(bufferOne.toString('utf8'));

// Output: This is a buffer example.

.toString() by default converts a buffer to a utf-8 format string. This is how you decode a buffer. If you specify an encoding you can convert the buffer to another encoding

console.log(bufferOne.toString('base64'));

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...