Buffer.from: Deno’s equivalent of Node.js
This is a part of the series: Deno’s equivalent of Node.js. In the brief articles that are part of this series, we explore the Deno equivalent of commonly used functions in Node.js. The articles are written in no particular order.
In this article, we’ll see the Deno’s equivalent of Node.js’s Buffer.from.
Buffer.from
Node.js’s Buffer.from is used to create a buffer from a variety of sources like:
- Array
- Buffer
- String
- Hex string
Let’s see how to do the same in Deno.
Except for array, there is no direct equivalent in Deno (not yet)
Imports
Node’s Buffer is part of the core module, while Deno’s Buffer is in both places (but will be out of the core runtime very soon). To use in the recommended way, import Deno’s Buffer from the standard library’s io module:
import {Buffer} from "https://deno.land/std/io/buffer.ts";
From array
- In Node.js, an array containing bytes can be directly used
- In Deno, an array containing bytes can be directly used
//Node.js
const a=Buffer.from(new Uint8Array(10).fill(65));//Deno
const a=new Buffer(new Uint8Array(10).fill(65));
From Buffer
- In Node.js, a buffer can be used directly
- In Deno, readFrom is required to use input Buffer as a Reader
//Node.js
const a=Buffer.from(new Uint8Array(10).fill(65));
const b=Buffer.from(a);//Deno
const b=new Buffer(new Uint8Array(10).fill(65));
const c=new Buffer();
c.readFrom(b);
From string
- In Node.js, a string can be directly given to the Buffer
- In Deno, a string needs to be encoded before giving to the Buffer
//Node.js
const a=Buffer.from('Hello World');//Deno
const a=new Buffer(new TextEncoder().encode('Hello World'));
From hex string
A hex string is an ASCII string contains bytes in hex format. For example —
string: Hello World
hex string: 48656c6c6f20576f726c64
- In Node.js, hex string can be used with encoding type as ‘hex’
- In Deno, hex string needs to be converted to bytes before giving to Buffer
//Node.js
Buffer.from('48656c6c6f20576f726c64', 'hex');//Deno
import {decodeString} from "https://deno.land/std/encoding/hex.ts";
new Buffer(decodeString('48656c6c6f20576f726c64'));
This story is a part of the exclusive medium publication on Deno: Deno World.