Home > Web Front-end > JS Tutorial > body text

Buffers: Node.js

Linda Hamilton
Release: 2024-10-08 06:31:02
Original
917 people have browsed it

Buffers: Node.js

Simple Guide to Buffers in Node.js

A Buffer in Node.js is used to handle raw binary data, which is useful when working with streams, files, or network data.

How to Create Buffers

  1. From a String:

   const buf = Buffer.from('Hello');


Copy after login
  1. Allocate a Buffer with a specific size:

   const buf = Buffer.alloc(10); // 10-byte buffer filled with zeros


Copy after login
  1. From an Array of bytes:

   const buf = Buffer.from([72, 101, 108, 108, 111]); // Represents 'Hello'


Copy after login

Important Buffer Functions

  1. Convert Buffer to String:

   const buf = Buffer.from('Hello');
   console.log(buf.toString()); // 'Hello'


Copy after login
  1. Get Buffer Length:

   const buf = Buffer.from('Hello');
   console.log(buf.length); // 5 (each character takes 1 byte)


Copy after login
  1. Write Data to Buffer:

   const buf = Buffer.alloc(5);
   buf.write('Hi');
   console.log(buf.toString()); // 'Hi'


Copy after login
  1. Slice a Buffer:

   const buf = Buffer.from('Hello World');
   const slice = buf.slice(0, 5);
   console.log(slice.toString()); // 'Hello'


Copy after login
  1. Copy from One Buffer to Another:

   const buf1 = Buffer.from('Hello');
   const buf2 = Buffer.alloc(5);
   buf1.copy(buf2);
   console.log(buf2.toString()); // 'Hello'


Copy after login
  1. Compare Two Buffers:

   const buf1 = Buffer.from('abc');
   const buf2 = Buffer.from('abc');
   console.log(buf1.equals(buf2)); // true


Copy after login
  1. Concatenate Multiple Buffers:

   const buf1 = Buffer.from('Hello');
   const buf2 = Buffer.from(' World');
   const buf3 = Buffer.concat([buf1, buf2]);
   console.log(buf3.toString()); // 'Hello World'


Copy after login

These are the key Buffer functions you need to know to start working with binary data in Node.js:

  • Create, write, and read Buffers
  • Slice, copy, compare, and concatenate Buffers

This is enough to handle most beginner use cases in Node.js!

The above is the detailed content of Buffers: Node.js. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!