Buffer#

安定性: 2 - Stable

ソースコード: lib/buffer.js

Bufferオブジェクトは、固定長のバイトシーケンスを表すために使用されます。多くのNode.js APIはBufferをサポートしています。

Bufferクラスは、JavaScriptの<Uint8Array>クラスのサブクラスであり、追加のユースケースをカバーするメソッドで拡張されています。Node.js APIは、Bufferがサポートされている場所であれば、プレーンな<Uint8Array>も同様に受け入れます。

Bufferクラスはグローバルスコープ内で利用可能ですが、importまたはrequireステートメントを介して明示的に参照することが推奨されます。

import { Buffer } from 'node:buffer';

// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);

// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);

// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);

// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);

// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);

// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');

// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');const { Buffer } = require('node:buffer');

// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);

// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);

// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);

// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);

// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);

// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');

// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');

Bufferと文字エンコーディング#

Bufferと文字列を相互に変換する際、文字エンコーディングを指定できます。文字エンコーディングが指定されていない場合、デフォルトでUTF-8が使用されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from('hello world', 'utf8');

console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=

console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>const { Buffer } = require('node:buffer');

const buf = Buffer.from('hello world', 'utf8');

console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=

console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>

Node.jsのバッファは、受け取ったエンコーディング文字列のあらゆる大文字小文字のバリエーションを受け入れます。例えば、UTF-8は'utf8''UTF8'、または'uTf8'として指定できます。

現在Node.jsでサポートされている文字エンコーディングは以下の通りです

  • 'utf8' (エイリアス: 'utf-8'): マルチバイトでエンコードされたUnicode文字。多くのウェブページやその他のドキュメント形式でUTF-8が使用されています。これはデフォルトの文字エンコーディングです。有効なUTF-8データのみを含まないBufferを文字列にデコードする際、それらのエラーを表すためにUnicode置換文字U+FFFD � が使用されます。

  • 'utf16le' (エイリアス: 'utf-16le'): マルチバイトでエンコードされたUnicode文字。'utf8'とは異なり、文字列の各文字は2または4バイトのいずれかを使用してエンコードされます。Node.jsはUTF-16リトルエンディアン版のみをサポートしています。

  • 'latin1': Latin-1はISO-8859-1を表します。この文字エンコーディングはU+0000からU+00FFまでのUnicode文字のみをサポートします。各文字は単一バイトを使用してエンコードされます。その範囲に収まらない文字は切り捨てられ、その範囲内の文字にマッピングされます。

上記のいずれかを使用してBufferを文字列に変換することをデコードと呼び、文字列をBufferに変換することをエンコードと呼びます。

Node.jsは、以下のバイナリからテキストへのエンコーディングもサポートしています。バイナリからテキストへのエンコーディングでは、命名規則が逆になります。通常、Bufferを文字列に変換することをエンコードと呼び、文字列をBufferに変換することをデコードと呼びます。

  • 'base64': Base64エンコーディング。文字列からBufferを作成する際、このエンコーディングはRFC 4648, Section 5で指定されている「URL and Filename Safe Alphabet」も正しく受け入れます。base64エンコードされた文字列に含まれるスペース、タブ、改行などの空白文字は無視されます。

  • 'base64url': RFC 4648, Section 5で指定されているbase64urlエンコーディング。文字列からBufferを作成する際、このエンコーディングは通常のbase64エンコードされた文字列も正しく受け入れます。Bufferを文字列にエンコードする際、このエンコーディングはパディングを省略します。

  • 'hex': 各バイトを2つの16進数文字としてエンコードします。偶数個の16進数文字のみで構成されていない文字列をデコードする際、データの切り捨てが発生する可能性があります。例については以下を参照してください。

以下のレガシー文字エンコーディングもサポートされています

  • 'ascii': 7ビットのASCIIデータ専用です。文字列をBufferにエンコードする際、これは'latin1'を使用するのと同等です。Bufferを文字列にデコードする際、このエンコーディングを使用すると、'latin1'としてデコードする前に各バイトの最上位ビットが追加でクリアされます。一般的に、ASCIIのみのテキストをエンコードまたはデコードする際には、'utf8'(またはデータが常にASCIIのみであることがわかっている場合は'latin1')がより良い選択であるため、このエンコーディングを使用する理由はないはずです。これはレガシー互換性のためにのみ提供されています。

  • 'binary': 'latin1'のエイリアス。ここにリストされているすべてのエンコーディングは文字列とバイナリデータを相互に変換するため、このエンコーディングの名前は非常に誤解を招く可能性があります。文字列とBufferの相互変換には、通常'utf8'が適切な選択です。

  • 'ucs2', 'ucs-2': 'utf16le'のエイリアス。UCS-2はかつて、U+FFFFより大きいコードポイントを持つ文字をサポートしないUTF-16の亜種を指していました。Node.jsでは、これらのコードポイントは常にサポートされています。

import { Buffer } from 'node:buffer';

Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.

Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').

Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.const { Buffer } = require('node:buffer');

Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.

Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').

Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.

現代のWebブラウザはWHATWG Encoding Standardに従っており、'latin1''ISO-8859-1'の両方を'win-1252'のエイリアスとしています。これは、http.get()のような操作を行う際に、返されたcharsetがWHATWG仕様にリストされているものの1つである場合、サーバーが実際に'win-1252'エンコードされたデータを返した可能性があり、'latin1'エンコーディングを使用すると文字が正しくデコードされない可能性があることを意味します。

BufferとTypedArray#

Bufferインスタンスは、JavaScriptの<Uint8Array>および<TypedArray>インスタンスでもあります。すべての<TypedArray>メソッドはBufferで利用可能です。ただし、Buffer APIと<TypedArray> APIの間には、微妙な非互換性があります。

特に

  • TypedArray.prototype.slice()TypedArrayの一部をコピーして新しいものを作成するのに対し、Buffer.prototype.slice()はコピーせずに既存のBuffer上のビューを作成します。この動作は意外かもしれませんが、レガシー互換性のためにのみ存在します。TypedArray.prototype.subarray()を使用すると、Bufferと他のTypedArrayの両方でBuffer.prototype.slice()の動作を実現でき、こちらを使用することが推奨されます。
  • buf.toString()は、そのTypedArray版と互換性がありません。
  • buf.indexOf()など、いくつかのメソッドは追加の引数をサポートします。

Bufferから新しい<TypedArray>インスタンスを作成するには、2つの方法があります

  • Buffer<TypedArray>コンストラクタに渡すと、Bufferの内容が整数の配列として解釈されてコピーされます。これはターゲット型のバイトシーケンスとしてではありません。
import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);

console.log(uint32array);

// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);

console.log(uint32array);

// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
import { Buffer } from 'node:buffer';

const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
  buf.buffer,
  buf.byteOffset,
  buf.length / Uint16Array.BYTES_PER_ELEMENT);

console.log(uint16array);

// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]const { Buffer } = require('node:buffer');

const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
  buf.buffer,
  buf.byteOffset,
  buf.length / Uint16Array.BYTES_PER_ELEMENT);

console.log(uint16array);

// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]

<TypedArray>インスタンスと同じ割り当てられたメモリを共有する新しいBufferを作成することが可能です。これは、TypedArrayオブジェクトの.bufferプロパティを同じ方法で使用することで行います。この文脈では、Buffer.from()new Uint8Array()のように動作します。

import { Buffer } from 'node:buffer';

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);

// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);

console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>

arr[1] = 6000;

console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);

// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);

console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>

arr[1] = 6000;

console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>

<TypedArray>.bufferを使用してBufferを作成する場合、byteOffsetlengthパラメータを渡すことで、基となる<ArrayBuffer>の一部のみを使用することが可能です。

import { Buffer } from 'node:buffer';

const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);

console.log(buf.length);
// Prints: 16const { Buffer } = require('node:buffer');

const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);

console.log(buf.length);
// Prints: 16

Buffer.from()TypedArray.from()は、シグネチャと実装が異なります。具体的には、<TypedArray>の亜種は、型付き配列のすべての要素に対して呼び出されるマッピング関数である第2引数を受け入れます

しかし、Buffer.from()メソッドはマッピング関数の使用をサポートしていません

Bufferとイテレーション#

Bufferインスタンスは、for..of構文を使用して反復処理できます

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3]);

for (const b of buf) {
  console.log(b);
}
// Prints:
//   1
//   2
//   3const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3]);

for (const b of buf) {
  console.log(b);
}
// Prints:
//   1
//   2
//   3

さらに、buf.values()buf.keys()、およびbuf.entries()メソッドを使用してイテレータを作成できます。

クラス: Blob#

<Blob>は、複数のワーカースレッド間で安全に共有できる、不変の生データをカプセル化します。

new buffer.Blob([sources[, options]])#

  • sources <string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> | <Blob[]> Blob内に格納される、string、<ArrayBuffer><TypedArray><DataView>、または<Blob>オブジェクトの配列、またはそれらのオブジェクトの任意の組み合わせ。
  • options <Object>
    • endings <string> 'transparent'または'native'のいずれか。'native'に設定すると、文字列ソース部分の行末は、require('node:os').EOLで指定されたプラットフォームネイティブの行末に変換されます。
    • type <string> Blobのコンテントタイプ。typeはデータのMIMEメディアタイプを伝えることを意図していますが、タイプ形式の検証は行われません。

与えられたソースを連結したものを含む新しいBlobオブジェクトを作成します。

<ArrayBuffer><TypedArray><DataView>、および<Buffer>ソースは「Blob」にコピーされるため、「Blob」が作成された後でも安全に変更できます。

文字列ソースはUTF-8バイトシーケンスとしてエンコードされ、Blobにコピーされます。各文字列部分内の不一致のサロゲートペアは、Unicode U+FFFD置換文字に置き換えられます。

blob.arrayBuffer()#

Blobデータのコピーを含む<ArrayBuffer>で解決されるPromiseを返します。

blob.bytes()#

blob.bytes()メソッドは、BlobオブジェクトのバイトをPromise<Uint8Array>として返します。

const blob = new Blob(['hello']);
blob.bytes().then((bytes) => {
  console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]
}); 

blob.size#

Blobの総サイズ(バイト単位)。

blob.slice([start[, end[, type]]])#

  • start <number> 開始インデックス。
  • end <number> 終了インデックス。
  • type <string> 新しいBlobのコンテントタイプ。

このBlobオブジェクトのデータのサブセットを含む新しいBlobを作成して返します。元のBlobは変更されません。

blob.stream()#

Blobのコンテンツを読み取ることができる新しいReadableStreamを返します。

blob.text()#

BlobのコンテンツをUTF-8文字列としてデコードしたもので解決されるPromiseを返します。

blob.type#

Blobのコンテントタイプ。

BlobオブジェクトとMessageChannel#

<Blob>オブジェクトが作成されると、データを転送したり即座にコピーしたりすることなく、MessagePort経由で複数の宛先に送信できます。Blobに含まれるデータは、arrayBuffer()またはtext()メソッドが呼び出されたときにのみコピーされます。

import { Blob } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';

const blob = new Blob(['hello there']);

const mc1 = new MessageChannel();
const mc2 = new MessageChannel();

mc1.port1.onmessage = async ({ data }) => {
  console.log(await data.arrayBuffer());
  mc1.port1.close();
};

mc2.port1.onmessage = async ({ data }) => {
  await delay(1000);
  console.log(await data.arrayBuffer());
  mc2.port1.close();
};

mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);

// The Blob is still usable after posting.
blob.text().then(console.log);const { Blob } = require('node:buffer');
const { setTimeout: delay } = require('node:timers/promises');

const blob = new Blob(['hello there']);

const mc1 = new MessageChannel();
const mc2 = new MessageChannel();

mc1.port1.onmessage = async ({ data }) => {
  console.log(await data.arrayBuffer());
  mc1.port1.close();
};

mc2.port1.onmessage = async ({ data }) => {
  await delay(1000);
  console.log(await data.arrayBuffer());
  mc2.port1.close();
};

mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);

// The Blob is still usable after posting.
blob.text().then(console.log);

クラス: Buffer#

Bufferクラスは、バイナリデータを直接扱うためのグローバルな型です。様々な方法で構築できます。

静的メソッド: Buffer.alloc(size[, fill[, encoding]])#

sizeバイトの新しいBufferを割り当てます。fillundefinedの場合、Bufferはゼロで埋められます。

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(5);

console.log(buf);
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(5);

console.log(buf);
// Prints: <Buffer 00 00 00 00 00>

sizebuffer.constants.MAX_LENGTHより大きいか、0より小さい場合、ERR_OUT_OF_RANGEがスローされます。

fillが指定されている場合、割り当てられたBufferbuf.fill(fill)を呼び出すことによって初期化されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(5, 'a');

console.log(buf);
// Prints: <Buffer 61 61 61 61 61>const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(5, 'a');

console.log(buf);
// Prints: <Buffer 61 61 61 61 61>

fillencodingの両方が指定されている場合、割り当てられたBufferbuf.fill(fill, encoding)を呼び出すことによって初期化されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');

console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');

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

Buffer.alloc()の呼び出しは、代替のBuffer.allocUnsafe()よりも著しく遅くなる可能性がありますが、新しく作成されたBufferインスタンスの内容が、Buffer用に割り当てられていない可能性のあるデータを含む、以前の割り当てからの機密データを含まないことを保証します。

sizeが数値でない場合、TypeErrorがスローされます。

静的メソッド: Buffer.allocUnsafe(size)#

sizeバイトの新しいBufferを割り当てます。sizebuffer.constants.MAX_LENGTHより大きいか、0より小さい場合、ERR_OUT_OF_RANGEがスローされます。

この方法で作成されたBufferインスタンスの基礎となるメモリは*初期化されません*。新しく作成されたBufferの内容は不明であり、*機密データを含む可能性があります*。Bufferインスタンスをゼロで初期化するには、代わりにBuffer.alloc()を使用してください。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(10);

console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>

buf.fill(0);

console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(10);

console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>

buf.fill(0);

console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>

sizeが数値でない場合、TypeErrorがスローされます。

Bufferモジュールは、Buffer.poolSizeサイズの内部Bufferインスタンスを事前に割り当てます。これは、sizeBuffer.poolSize >>> 1Buffer.poolSizeを2で割った床値)より小さい場合にのみ、Buffer.allocUnsafe()Buffer.from(array)Buffer.from(string)、およびBuffer.concat()を使用して作成される新しいBufferインスタンスの高速割り当てのためのプールとして使用されます。

この事前に割り当てられた内部メモリプールの使用は、Buffer.alloc(size, fill)Buffer.allocUnsafe(size).fill(fill)を呼び出すことの重要な違いです。具体的には、Buffer.alloc(size, fill)は内部Bufferプールを*決して*使用しませんが、Buffer.allocUnsafe(size).fill(fill)は、sizeBuffer.poolSizeの半分以下の場合に内部Bufferプールを*使用します*。この違いは微妙ですが、アプリケーションがBuffer.allocUnsafe()が提供する追加のパフォーマンスを必要とする場合には重要になることがあります。

静的メソッド: Buffer.allocUnsafeSlow(size)#

sizeバイトの新しいBufferを割り当てます。sizebuffer.constants.MAX_LENGTHより大きいか、0より小さい場合、ERR_OUT_OF_RANGEがスローされます。sizeが0の場合、ゼロ長のBufferが作成されます。

この方法で作成されたBufferインスタンスの基礎となるメモリは*初期化されません*。新しく作成されたBufferの内容は不明であり、*機密データを含む可能性があります*。そのようなBufferインスタンスをゼロで初期化するには、buf.fill(0)を使用してください。

Buffer.allocUnsafe()を使用して新しいBufferインスタンスを割り当てる際、Buffer.poolSize >>> 1(デフォルトのpoolSizeが使用される場合は4KiB)未満の割り当ては、単一の事前に割り当てられたBufferからスライスされます。これにより、アプリケーションは多数の個別に割り当てられたBufferインスタンスを作成することによるガベージコレクションのオーバーヘッドを回避できます。このアプローチは、追跡およびクリーンアップする必要のある個別のArrayBufferオブジェクトの数を減らすことにより、パフォーマンスとメモリ使用量の両方を向上させます。

しかし、開発者が不確定な期間、プールからメモリの小さなチャンクを保持する必要がある場合、Buffer.allocUnsafeSlow()を使用してプールされていないBufferインスタンスを作成し、関連するビットをコピーアウトすることが適切な場合があります。

import { Buffer } from 'node:buffer';

// Need to keep around a few small chunks of memory.
const store = [];

socket.on('readable', () => {
  let data;
  while (null !== (data = readable.read())) {
    // Allocate for retained data.
    const sb = Buffer.allocUnsafeSlow(10);

    // Copy the data into the new allocation.
    data.copy(sb, 0, 0, 10);

    store.push(sb);
  }
});const { Buffer } = require('node:buffer');

// Need to keep around a few small chunks of memory.
const store = [];

socket.on('readable', () => {
  let data;
  while (null !== (data = readable.read())) {
    // Allocate for retained data.
    const sb = Buffer.allocUnsafeSlow(10);

    // Copy the data into the new allocation.
    data.copy(sb, 0, 0, 10);

    store.push(sb);
  }
});

sizeが数値でない場合、TypeErrorがスローされます。

静的メソッド: Buffer.byteLength(string[, encoding])#

encodingを使用してエンコードされた場合の文字列のバイト長を返します。これは、文字列をバイトに変換するために使用されるエンコーディングを考慮しないString.prototype.lengthとは異なります。

'base64''base64url'、および'hex'の場合、この関数は有効な入力を想定します。非base64/hexエンコードデータ(例:空白)を含む文字列の場合、戻り値は文字列から作成されたBufferの長さより大きい場合があります。

import { Buffer } from 'node:buffer';

const str = '\u00bd + \u00bc = \u00be';

console.log(`${str}: ${str.length} characters, ` +
            `${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytesconst { Buffer } = require('node:buffer');

const str = '\u00bd + \u00bc = \u00be';

console.log(`${str}: ${str.length} characters, ` +
            `${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes

string<Buffer> | <DataView> | <TypedArray> | <ArrayBuffer> | <SharedArrayBuffer>の場合、.byteLengthによって報告されるバイト長が返されます。

静的メソッド: Buffer.compare(buf1, buf2)#

buf1buf2と比較します。通常はBufferインスタンスの配列をソートする目的で使用されます。これはbuf1.compare(buf2)を呼び出すことと同等です。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];

console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)const { Buffer } = require('node:buffer');

const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];

console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)

静的メソッド: Buffer.concat(list[, totalLength])#

list内のすべてのBufferインスタンスを連結した結果である新しいBufferを返します。

リストに項目がない場合、またはtotalLengthが0の場合、新しいゼロ長のBufferが返されます。

totalLengthが提供されない場合、list内のBufferインスタンスから、それらの長さを加算して計算されます。

totalLengthが提供された場合、それは符号なし整数に強制変換されます。list内のBufferの合計長がtotalLengthを超える場合、結果はtotalLengthに切り捨てられます。list内のBufferの合計長がtotalLengthより短い場合、残りのスペースはゼロで埋められます。

import { Buffer } from 'node:buffer';

// Create a single `Buffer` from a list of three `Buffer` instances.

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;

console.log(totalLength);
// Prints: 42

const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);

console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42const { Buffer } = require('node:buffer');

// Create a single `Buffer` from a list of three `Buffer` instances.

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;

console.log(totalLength);
// Prints: 42

const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);

console.log(bufA);
// Prints: <Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42

Buffer.concat()は、Buffer.allocUnsafe()のように内部のBufferプールを使用することもあります。

静的メソッド: Buffer.copyBytesFrom(view[, offset[, length]])#

viewの基礎となるメモリを新しいBufferにコピーします。

const u16 = new Uint16Array([0, 0xffff]);
const buf = Buffer.copyBytesFrom(u16, 1, 1);
u16[1] = 0;
console.log(buf.length); // 2
console.log(buf[0]); // 255
console.log(buf[1]); // 255 

静的メソッド: Buffer.from(array)#

0から255の範囲のバイトのarrayを使用して新しいBufferを割り当てます。その範囲外の配列エントリは、それに収まるように切り捨てられます。

import { Buffer } from 'node:buffer';

// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);const { Buffer } = require('node:buffer');

// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);

arrayArrayライクなオブジェクト(つまり、number型のlengthプロパティを持つオブジェクト)である場合、それがBufferまたはUint8Arrayでない限り、配列として扱われます。これは、他のすべてのTypedArrayの亜種がArrayとして扱われることを意味します。TypedArrayをバックアップするバイトからBufferを作成するには、Buffer.copyBytesFrom()を使用してください。

arrayArrayまたはBuffer.from()の他のバリアントに適した型でない場合、TypeErrorがスローされます。

Buffer.from(array)Buffer.from(string)は、Buffer.allocUnsafe()のように内部のBufferプールを使用することもあります。

静的メソッド: Buffer.from(arrayBuffer[, byteOffset[, length]])#

これは、基礎となるメモリをコピーすることなく、<ArrayBuffer>のビューを作成します。例えば、<TypedArray>インスタンスの.bufferプロパティへの参照を渡した場合、新しく作成されたBufferは、<TypedArray>の基礎となるArrayBufferと同じ割り当てられたメモリを共有します。

import { Buffer } from 'node:buffer';

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);

console.log(buf);
// Prints: <Buffer 88 13 a0 0f>

// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;

console.log(buf);
// Prints: <Buffer 88 13 70 17>const { Buffer } = require('node:buffer');

const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);

console.log(buf);
// Prints: <Buffer 88 13 a0 0f>

// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;

console.log(buf);
// Prints: <Buffer 88 13 70 17>

オプションのbyteOffsetlength引数は、Bufferによって共有されるarrayBuffer内のメモリ範囲を指定します。

import { Buffer } from 'node:buffer';

const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);

console.log(buf.length);
// Prints: 2const { Buffer } = require('node:buffer');

const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);

console.log(buf.length);
// Prints: 2

arrayBuffer<ArrayBuffer>または<SharedArrayBuffer>、またはBuffer.from()の他のバリアントに適した型でない場合、TypeErrorがスローされます。

バッキングArrayBufferTypedArrayビューの境界を超えてメモリの範囲をカバーできることを覚えておくことが重要です。TypedArraybufferプロパティを使用して作成された新しいBufferは、TypedArrayの範囲を超える可能性があります。

import { Buffer } from 'node:buffer';

const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true

const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>const { Buffer } = require('node:buffer');

const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true

const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>

静的メソッド: Buffer.from(buffer)#

渡されたbufferのデータを新しいBufferインスタンスにコピーします。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);

buf1[0] = 0x61;

console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: bufferconst { Buffer } = require('node:buffer');

const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);

buf1[0] = 0x61;

console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer

bufferBufferまたはBuffer.from()の他のバリアントに適した型でない場合、TypeErrorがスローされます。

静的メソッド: Buffer.from(object[, offsetOrEncoding[, length]])#

  • object <Object> Symbol.toPrimitiveまたはvalueOf()をサポートするオブジェクト。
  • offsetOrEncoding <integer> | <string> バイトオフセットまたはエンコーディング。
  • length <integer> 長さ。
  • 戻り値: <Buffer>

valueOf()関数がobjectと厳密に等しくない値を返すオブジェクトの場合、Buffer.from(object.valueOf(), offsetOrEncoding, length)を返します。

import { Buffer } from 'node:buffer';

const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');

const buf = Buffer.from(new String('this is a test'));
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>

Symbol.toPrimitiveをサポートするオブジェクトの場合、Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)を返します。

import { Buffer } from 'node:buffer';

class Foo {
  [Symbol.toPrimitive]() {
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>const { Buffer } = require('node:buffer');

class Foo {
  [Symbol.toPrimitive]() {
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>

objectが言及されたメソッドを持たないか、Buffer.from()の他のバリアントに適した他の型でない場合、TypeErrorがスローされます。

静的メソッド: Buffer.from(string[, encoding])#

  • string <string> エンコードする文字列。
  • encoding <string> stringのエンコーディング。デフォルト: 'utf8'
  • 戻り値: <Buffer>

stringを含む新しいBufferを作成します。encodingパラメータは、stringをバイトに変換する際に使用される文字エンコーディングを特定します。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a téstconst { Buffer } = require('node:buffer');

const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a tést

stringが文字列またはBuffer.from()の他のバリアントに適した他の型でない場合、TypeErrorがスローされます。

Buffer.from(string)は、Buffer.allocUnsafe()のように内部のBufferプールを使用することもあります。

静的メソッド: Buffer.isBuffer(obj)#

objBufferの場合はtrueを、それ以外の場合はfalseを返します。

import { Buffer } from 'node:buffer';

Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // falseconst { Buffer } = require('node:buffer');

Buffer.isBuffer(Buffer.alloc(10)); // true
Buffer.isBuffer(Buffer.from('foo')); // true
Buffer.isBuffer('a string'); // false
Buffer.isBuffer([]); // false
Buffer.isBuffer(new Uint8Array(1024)); // false

静的メソッド: Buffer.isEncoding(encoding)#

  • encoding <string> チェックする文字エンコーディング名。
  • 戻り値: <boolean>

encodingがサポートされている文字エンコーディングの名前である場合はtrueを、それ以外の場合はfalseを返します。

import { Buffer } from 'node:buffer';

console.log(Buffer.isEncoding('utf8'));
// Prints: true

console.log(Buffer.isEncoding('hex'));
// Prints: true

console.log(Buffer.isEncoding('utf/8'));
// Prints: false

console.log(Buffer.isEncoding(''));
// Prints: falseconst { Buffer } = require('node:buffer');

console.log(Buffer.isEncoding('utf8'));
// Prints: true

console.log(Buffer.isEncoding('hex'));
// Prints: true

console.log(Buffer.isEncoding('utf/8'));
// Prints: false

console.log(Buffer.isEncoding(''));
// Prints: false

Buffer.poolSize#

これは、プーリングに使用される事前に割り当てられた内部Bufferインスタンスのサイズ(バイト単位)です。この値は変更可能です。

buf[index]#

インデックス演算子[index]を使用して、buf内の位置indexにあるオクテットを取得および設定できます。値は個々のバイトを参照するため、有効な値の範囲は0x00から0xFF(16進数)または0から255(10進数)の間です。

この演算子はUint8Arrayから継承されているため、範囲外のアクセスに対する動作はUint8Arrayと同じです。つまり、indexが負またはbuf.length以上の場合、buf[index]undefinedを返し、indexが負または>= buf.lengthの場合、buf[index] = valueはバッファを変更しません。

import { Buffer } from 'node:buffer';

// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)

const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);

for (let i = 0; i < str.length; i++) {
  buf[i] = str.charCodeAt(i);
}

console.log(buf.toString('utf8'));
// Prints: Node.jsconst { Buffer } = require('node:buffer');

// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)

const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);

for (let i = 0; i < str.length; i++) {
  buf[i] = str.charCodeAt(i);
}

console.log(buf.toString('utf8'));
// Prints: Node.js

buf.buffer#

  • 型: <ArrayBuffer> このBufferオブジェクトが作成された基礎となるArrayBufferオブジェクト。

このArrayBufferが元のBufferと正確に対応することは保証されません。詳細については、buf.byteOffsetの注記を参照してください。

import { Buffer } from 'node:buffer';

const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);

console.log(buffer.buffer === arrayBuffer);
// Prints: trueconst { Buffer } = require('node:buffer');

const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);

console.log(buffer.buffer === arrayBuffer);
// Prints: true

buf.byteOffset#

  • 型: <integer> Bufferの基礎となるArrayBufferオブジェクトのbyteOffset

Buffer.from(ArrayBuffer, byteOffset, length)byteOffsetを設定する場合、または時々Buffer.poolSizeより小さいBufferを割り当てる場合、バッファは基礎となるArrayBuffer上のゼロオフセットから開始しません。

これは、buf.bufferを使用して基礎となるArrayBufferに直接アクセスするときに問題を引き起こす可能性があります。なぜなら、ArrayBufferの他の部分はBufferオブジェクト自体とは無関係である可能性があるためです。

Bufferとメモリを共有するTypedArrayオブジェクトを作成する際の一般的な問題は、この場合、byteOffsetを正しく指定する必要があることです。

import { Buffer } from 'node:buffer';

// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);const { Buffer } = require('node:buffer');

// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);

buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])#

  • target <Buffer> | <Uint8Array> bufと比較するBufferまたは<Uint8Array>
  • targetStart <integer> 比較を開始するtarget内のオフセット。デフォルト: 0
  • targetEnd <integer> 比較を終了するtarget内のオフセット(含まない)。デフォルト: target.length
  • sourceStart <integer> 比較を開始するbuf内のオフセット。デフォルト: 0
  • sourceEnd <integer> 比較を終了するbuf内のオフセット(含まない)。デフォルト: buf.length
  • 戻り値: <integer>

buftargetと比較し、bufがソート順でtargetの前、後、または同じであるかを示す数値を返します。比較は、各Bufferの実際のバイトシーケンスに基づいています。

  • targetbufと同じ場合、0が返されます。
  • ソート時にtargetbufの*前*に来るべき場合、1が返されます。
  • ソート時にtargetbufの*後*に来るべき場合、-1が返されます。
import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');

console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)const { Buffer } = require('node:buffer');

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');

console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)

オプションのtargetStarttargetEndsourceStart、およびsourceEnd引数を使用して、比較をそれぞれtargetbuf内の特定の範囲に制限できます。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);

console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1const { Buffer } = require('node:buffer');

const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);

console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1

targetStart < 0sourceStart < 0targetEnd > target.byteLength、またはsourceEnd > source.byteLengthの場合、ERR_OUT_OF_RANGEがスローされます。

buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])#

  • target <Buffer> | <Uint8Array> コピー先のBufferまたは<Uint8Array>
  • targetStart <integer> 書き込みを開始するtarget内のオフセット。デフォルト: 0
  • sourceStart <integer> コピーを開始するbufからのオフセット。デフォルト: 0
  • sourceEnd <integer> コピーを停止するbuf内のオフセット(含まない)。デフォルト: buf.length
  • 戻り値: <integer> コピーされたバイト数。

targetのメモリ領域がbufと重なっていても、bufの領域からtargetの領域へデータをコピーします。

TypedArray.prototype.set()は同じ操作を実行し、Node.jsのBufferを含むすべてのTypedArrayで利用可能ですが、異なる関数引数を取ります。

import { Buffer } from 'node:buffer';

// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
buf1.copy(buf2, 8, 16, 20);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);

console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!const { Buffer } = require('node:buffer');

// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
buf1.copy(buf2, 8, 16, 20);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);

console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
import { Buffer } from 'node:buffer';

// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.

const buf = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf[i] = i + 97;
}

buf.copy(buf, 0, 4, 10);

console.log(buf.toString());
// Prints: efghijghijklmnopqrstuvwxyzconst { Buffer } = require('node:buffer');

// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.

const buf = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf[i] = i + 97;
}

buf.copy(buf, 0, 4, 10);

console.log(buf.toString());
// Prints: efghijghijklmnopqrstuvwxyz

buf.entries()#

bufの内容から[index, byte]ペアのイテレータを作成して返します。

import { Buffer } from 'node:buffer';

// Log the entire contents of a `Buffer`.

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

for (const pair of buf.entries()) {
  console.log(pair);
}
// Prints:
//   [0, 98]
//   [1, 117]
//   [2, 102]
//   [3, 102]
//   [4, 101]
//   [5, 114]const { Buffer } = require('node:buffer');

// Log the entire contents of a `Buffer`.

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

for (const pair of buf.entries()) {
  console.log(pair);
}
// Prints:
//   [0, 98]
//   [1, 117]
//   [2, 102]
//   [3, 102]
//   [4, 101]
//   [5, 114]

buf.equals(otherBuffer)#

bufotherBufferの両方がまったく同じバイトを持つ場合はtrueを、それ以外の場合はfalseを返します。buf.compare(otherBuffer) === 0と同等です。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');

console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: falseconst { Buffer } = require('node:buffer');

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');

console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: false

buf.fill(value[, offset[, end]][, encoding])#

  • value <string> | <Buffer> | <Uint8Array> | <integer> bufを埋める値。空の値(文字列、Uint8Array、Buffer)は0に強制変換されます。
  • offset <integer> bufの埋め込みを開始する前にスキップするバイト数。デフォルト: 0
  • end <integer> bufの埋め込みを停止する場所(含まない)。デフォルト: buf.length
  • encoding <string> valueが文字列の場合のvalueのエンコーディング。デフォルト: 'utf8'
  • 戻り値: <Buffer> bufへの参照。

bufを指定されたvalueで埋めます。offsetendが指定されない場合、buf全体が埋められます。

import { Buffer } from 'node:buffer';

// Fill a `Buffer` with the ASCII character 'h'.

const b = Buffer.allocUnsafe(50).fill('h');

console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');

console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>const { Buffer } = require('node:buffer');

// Fill a `Buffer` with the ASCII character 'h'.

const b = Buffer.allocUnsafe(50).fill('h');

console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

// Fill a buffer with empty string
const c = Buffer.allocUnsafe(5).fill('');

console.log(c.fill(''));
// Prints: <Buffer 00 00 00 00 00>

valueが文字列、Buffer、または整数でない場合、uint32値に強制変換されます。結果の整数が255(10進数)より大きい場合、bufvalue & 255で埋められます。

fill()操作の最後の書き込みがマルチバイト文字にかかる場合、bufに収まるその文字のバイトのみが書き込まれます。

import { Buffer } from 'node:buffer';

// Fill a `Buffer` with character that takes up two bytes in UTF-8.

console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>const { Buffer } = require('node:buffer');

// Fill a `Buffer` with character that takes up two bytes in UTF-8.

console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: <Buffer c8 a2 c8 a2 c8>

valueに無効な文字が含まれている場合、それは切り捨てられます。有効なフィルデータが残らない場合、例外がスローされます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(5);

console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(5);

console.log(buf.fill('a'));
// Prints: <Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: <Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.

buf.includes(value[, byteOffset][, encoding])#

  • value <string> | <Buffer> | <Uint8Array> | <integer> 検索する対象。
  • byteOffset <integer> buf内で検索を開始する場所。負の場合、オフセットはbufの末尾から計算されます。デフォルト: 0
  • encoding <string> valueが文字列の場合、そのエンコーディングです。デフォルト: 'utf8'
  • 戻り値: <boolean> buf内でvalueが見つかった場合はtrue、それ以外の場合はfalse

buf.indexOf() !== -1と同等です。

import { Buffer } from 'node:buffer';

const buf = Buffer.from('this is a buffer');

console.log(buf.includes('this'));
// Prints: true
console.log(buf.includes('is'));
// Prints: true
console.log(buf.includes(Buffer.from('a buffer')));
// Prints: true
console.log(buf.includes(97));
// Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example')));
// Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
// Prints: true
console.log(buf.includes('this', 4));
// Prints: falseconst { Buffer } = require('node:buffer');

const buf = Buffer.from('this is a buffer');

console.log(buf.includes('this'));
// Prints: true
console.log(buf.includes('is'));
// Prints: true
console.log(buf.includes(Buffer.from('a buffer')));
// Prints: true
console.log(buf.includes(97));
// Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example')));
// Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
// Prints: true
console.log(buf.includes('this', 4));
// Prints: false

buf.indexOf(value[, byteOffset][, encoding])#

  • value <string> | <Buffer> | <Uint8Array> | <integer> 検索する対象。
  • byteOffset <integer> buf内で検索を開始する場所。負の場合、オフセットはbufの末尾から計算されます。デフォルト: 0
  • encoding <string> valueが文字列の場合、これはbuf内で検索される文字列のバイナリ表現を決定するために使用されるエンコーディングです。デフォルト: 'utf8'
  • 戻り値: <integer> buf内でvalueが最初に出現したインデックス、またはbufvalueが含まれていない場合は-1

value

  • 文字列の場合、valueencodingの文字エンコーディングに従って解釈されます。
  • Bufferまたは<Uint8Array>の場合、valueは全体として使用されます。部分的なBufferを比較するには、buf.subarrayを使用してください。
  • 数値の場合、value0から255の間の符号なし8ビット整数値として解釈されます。
import { Buffer } from 'node:buffer';

const buf = Buffer.from('this is a buffer');

console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6const { Buffer } = require('node:buffer');

const buf = Buffer.from('this is a buffer');

console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6

valueが文字列、数値、またはBufferでない場合、このメソッドはTypeErrorをスローします。valueが数値の場合、それは有効なバイト値、つまり0から255の間の整数に強制変換されます。

byteOffsetが数値でない場合、それは数値に強制変換されます。強制変換の結果がNaNまたは0の場合、バッファ全体が検索されます。この動作はString.prototype.indexOf()と一致します。

import { Buffer } from 'node:buffer';

const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));

// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));const { Buffer } = require('node:buffer');

const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));

// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));

valueが空の文字列または空のBufferで、byteOffsetbuf.lengthより小さい場合、byteOffsetが返されます。valueが空でbyteOffsetbuf.length以上の場合、buf.lengthが返されます。

buf.keys()#

bufのキー(インデックス)のイテレータを作成して返します。

import { Buffer } from 'node:buffer';

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

for (const key of buf.keys()) {
  console.log(key);
}
// Prints:
//   0
//   1
//   2
//   3
//   4
//   5const { Buffer } = require('node:buffer');

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

for (const key of buf.keys()) {
  console.log(key);
}
// Prints:
//   0
//   1
//   2
//   3
//   4
//   5

buf.lastIndexOf(value[, byteOffset][, encoding])#

  • value <string> | <Buffer> | <Uint8Array> | <integer> 検索する対象。
  • byteOffset <integer> buf内で検索を開始する場所。負の場合、オフセットはbufの末尾から計算されます。デフォルト: buf.length - 1
  • encoding <string> valueが文字列の場合、これはbuf内で検索される文字列のバイナリ表現を決定するために使用されるエンコーディングです。デフォルト: 'utf8'
  • 戻り値: <integer> buf内でvalueが最後に出現したインデックス、またはbufvalueが含まれていない場合は-1

buf.indexOf()と同一ですが、valueの最初の出現ではなく最後の出現が見つかります。

import { Buffer } from 'node:buffer';

const buf = Buffer.from('this buffer is a buffer');

console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4const { Buffer } = require('node:buffer');

const buf = Buffer.from('this buffer is a buffer');

console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4

valueが文字列、数値、またはBufferでない場合、このメソッドはTypeErrorをスローします。valueが数値の場合、それは有効なバイト値、つまり0から255の間の整数に強制変換されます。

byteOffsetが数値でない場合、それは数値に強制変換されます。{}undefinedのようにNaNに強制変換される引数は、バッファ全体を検索します。この動作はString.prototype.lastIndexOf()と一致します。

import { Buffer } from 'node:buffer';

const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));

// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));

// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));const { Buffer } = require('node:buffer');

const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));

// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));

// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));

valueが空の文字列または空のBufferの場合、byteOffsetが返されます。

buf.length#

buf内のバイト数を返します。

import { Buffer } from 'node:buffer';

// Create a `Buffer` and write a shorter string to it using UTF-8.

const buf = Buffer.alloc(1234);

console.log(buf.length);
// Prints: 1234

buf.write('some string', 0, 'utf8');

console.log(buf.length);
// Prints: 1234const { Buffer } = require('node:buffer');

// Create a `Buffer` and write a shorter string to it using UTF-8.

const buf = Buffer.alloc(1234);

console.log(buf.length);
// Prints: 1234

buf.write('some string', 0, 'utf8');

console.log(buf.length);
// Prints: 1234

buf.parent#

安定性: 0 - 非推奨: 代わりにbuf.bufferを使用してください。

buf.parentプロパティは、buf.bufferの非推奨のエイリアスです。

buf.readBigInt64BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <bigint>

指定されたoffsetbufから符号付き、ビッグエンディアンの64ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

buf.readBigInt64LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <bigint>

指定されたoffsetbufから符号付き、リトルエンディアンの64ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

buf.readBigUInt64BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <bigint>

指定されたoffsetbufから符号なし、ビッグエンディアンの64ビット整数を読み取ります。

この関数はreadBigUint64BEエイリアスでも利用可能です。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);

console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295nconst { Buffer } = require('node:buffer');

const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);

console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n

buf.readBigUInt64LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <bigint>

指定されたoffsetbufから符号なし、リトルエンディアンの64ビット整数を読み取ります。

この関数はreadBigUint64LEエイリアスでも利用可能です。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);

console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320nconst { Buffer } = require('node:buffer');

const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);

console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n

buf.readDoubleBE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <number>

指定されたoffsetbufから64ビット、ビッグエンディアンのdoubleを読み取ります。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304

buf.readDoubleLE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8を満たす必要があります。デフォルト: 0
  • 戻り値: <number>

指定されたoffsetbufから64ビット、リトルエンディアンのdoubleを読み取ります。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.

buf.readFloatBE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <number>

指定されたoffsetbufから32ビット、ビッグエンディアンのfloatを読み取ります。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3, 4]);

console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3, 4]);

console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38

buf.readFloatLE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <number>

指定されたoffsetbufから32ビット、リトルエンディアンのfloatを読み取ります。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, 2, 3, 4]);

console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, 2, 3, 4]);

console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.

buf.readInt8([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 1を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定されたoffsetbufから符号付き8ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([-1, 5]);

console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([-1, 5]);

console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.

buf.readInt16BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定されたoffsetbufから符号付き、ビッグエンディアンの16ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0, 5]);

console.log(buf.readInt16BE(0));
// Prints: 5const { Buffer } = require('node:buffer');

const buf = Buffer.from([0, 5]);

console.log(buf.readInt16BE(0));
// Prints: 5

buf.readInt16LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号付きリトルエンディアン 16 ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0, 5]);

console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0, 5]);

console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.

buf.readInt32BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号付きビッグエンディアン 32 ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0, 0, 0, 5]);

console.log(buf.readInt32BE(0));
// Prints: 5const { Buffer } = require('node:buffer');

const buf = Buffer.from([0, 0, 0, 5]);

console.log(buf.readInt32BE(0));
// Prints: 5

buf.readInt32LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号付きリトルエンディアン 32 ビット整数を読み取ります。

Bufferから読み取られた整数は、2の補数符号付き値として解釈されます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0, 0, 0, 5]);

console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0, 0, 0, 5]);

console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.

buf.readIntBE(offset, byteLength)#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 読み取るバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer>

指定された offsetbuf から byteLength バイトを読み取り、結果を最大 48 ビットの精度をサポートするビッグエンディアンの 2 の補数符号付き値として解釈します。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.

buf.readIntLE(offset, byteLength)#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 読み取るバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer>

指定された offsetbuf から byteLength バイトを読み取り、結果を最大 48 ビットの精度をサポートするリトルエンディアンの 2 の補数符号付き値として解釈します。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbeeconst { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee

buf.readUInt8([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 1を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から符号なし 8 ビット整数を読み取ります。

この関数は readUint8 エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([1, -2]);

console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([1, -2]);

console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.

buf.readUInt16BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号なしビッグエンディアン 16 ビット整数を読み取ります。

この関数は readUint16BE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56]);

console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56]);

console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456

buf.readUInt16LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号なしリトルエンディアン 16 ビット整数を読み取ります。

この関数は readUint16LE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56]);

console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56]);

console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.

buf.readUInt32BE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号なしビッグエンディアン 32 ビット整数を読み取ります。

この関数は readUint32BE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678

buf.readUInt32LE([offset])#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4を満たす必要があります。デフォルト: 0
  • 戻り値: <integer>

指定された offsetbuf から、符号なしリトルエンディアン 32 ビット整数を読み取ります。

この関数は readUint32LE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.

buf.readUIntBE(offset, byteLength)#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 読み取るバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer>

指定された offsetbuf から byteLength バイトを読み取り、結果を最大 48 ビットの精度をサポートする符号なしビッグエンディアン整数として解釈します。

この関数は readUintBE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.

buf.readUIntLE(offset, byteLength)#

  • offset <integer> 読み取りを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 読み取るバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer>

指定された offsetbuf から byteLength バイトを読み取り、結果を最大 48 ビットの精度をサポートする符号なしリトルエンディアン整数として解釈します。

この関数は readUintLE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412

buf.subarray([start[, end]])#

  • start <integer> 新しい Buffer が開始する場所。デフォルト: 0
  • end <integer> 新しい Buffer が終了する場所 (このインデックスは含まれません)。デフォルト: buf.length
  • 戻り値: <Buffer>

元の Buffer と同じメモリを参照する新しい Buffer を返しますが、startend インデックスによってオフセットおよび切り取られます。

buf.length より大きい end を指定すると、endbuf.length と等しい場合と同じ結果が返されます。

このメソッドは TypedArray.prototype.subarray() から継承されます。

新しい Buffer スライスを変更すると、2つのオブジェクトの割り当てられたメモリが重複しているため、元の Buffer のメモリが変更されます。

import { Buffer } from 'node:buffer';

// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

const buf2 = buf1.subarray(0, 3);

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc

buf1[0] = 33;

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bcconst { Buffer } = require('node:buffer');

// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

const buf2 = buf1.subarray(0, 3);

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc

buf1[0] = 33;

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bc

負のインデックスを指定すると、スライスは buf の先頭からではなく、末尾から相対的に生成されます。

import { Buffer } from 'node:buffer';

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

console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)

console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)

console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)const { Buffer } = require('node:buffer');

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

console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)

console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)

console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)

buf.slice([start[, end]])#

  • start <integer> 新しい Buffer が開始する場所。デフォルト: 0
  • end <integer> 新しい Buffer が終了する場所 (このインデックスは含まれません)。デフォルト: buf.length
  • 戻り値: <Buffer>

安定性: 0 - 非推奨: 代わりに buf.subarray を使用してください。

元の Buffer と同じメモリを参照する新しい Buffer を返しますが、startend インデックスによってオフセットおよび切り取られます。

このメソッドは Buffer のスーパークラスである Uint8Array.prototype.slice() と互換性がありません。スライスをコピーするには、Uint8Array.prototype.slice() を使用してください。

import { Buffer } from 'node:buffer';

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

const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer

console.log(buf.toString());
// Prints: buffer

// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)const { Buffer } = require('node:buffer');

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

const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer

console.log(buf.toString());
// Prints: buffer

// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)

buf.swap16()#

  • 戻り値: <Buffer> bufへの参照。

buf を符号なし 16 ビット整数の配列として解釈し、バイト順をインプレースでスワップします。buf.length が 2 の倍数でない場合、ERR_INVALID_BUFFER_SIZE をスローします。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap16();

console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap16();

console.log(buf1);
// Prints: <Buffer 02 01 04 03 06 05 08 07>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.

buf.swap16() の便利な使い方の1つは、UTF-16 リトルエンディアンと UTF-16 ビッグエンディアン間の高速なインプレース変換を実行することです。

import { Buffer } from 'node:buffer';

const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.const { Buffer } = require('node:buffer');

const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.

buf.swap32()#

  • 戻り値: <Buffer> bufへの参照。

buf を符号なし 32 ビット整数の配列として解釈し、バイト順をインプレースでスワップします。buf.length が 4 の倍数でない場合、ERR_INVALID_BUFFER_SIZE をスローします。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap32();

console.log(buf1);
// Prints: <Buffer 04 03 02 01 08 07 06 05>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap32();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap32();

console.log(buf1);
// Prints: <Buffer 04 03 02 01 08 07 06 05>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap32();
// Throws ERR_INVALID_BUFFER_SIZE.

buf.swap64()#

  • 戻り値: <Buffer> bufへの参照。

buf を 64 ビット数の配列として解釈し、バイト順をインプレースでスワップします。buf.length が 8 の倍数でない場合、ERR_INVALID_BUFFER_SIZE をスローします。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap64();

console.log(buf1);
// Prints: <Buffer 08 07 06 05 04 03 02 01>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap64();
// Throws ERR_INVALID_BUFFER_SIZE.const { Buffer } = require('node:buffer');

const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf1.swap64();

console.log(buf1);
// Prints: <Buffer 08 07 06 05 04 03 02 01>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap64();
// Throws ERR_INVALID_BUFFER_SIZE.

buf.toJSON()#

buf の JSON 表現を返します。JSON.stringify() は、Buffer インスタンスを文字列化するときにこの関数を暗黙的に呼び出します。

Buffer.from() は、このメソッドから返される形式のオブジェクトを受け入れます。特に、Buffer.from(buf.toJSON())Buffer.from(buf) のように機能します。

import { Buffer } from 'node:buffer';

const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);

console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}

const copy = JSON.parse(json, (key, value) => {
  return value && value.type === 'Buffer' ?
    Buffer.from(value) :
    value;
});

console.log(copy);
// Prints: <Buffer 01 02 03 04 05>const { Buffer } = require('node:buffer');

const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);

console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}

const copy = JSON.parse(json, (key, value) => {
  return value && value.type === 'Buffer' ?
    Buffer.from(value) :
    value;
});

console.log(copy);
// Prints: <Buffer 01 02 03 04 05>

buf.toString([encoding[, start[, end]]])#

  • encoding <string> 使用する文字エンコーディング。デフォルト: 'utf8'
  • start <integer> デコードを開始するバイトオフセット。デフォルト: 0
  • end <integer> デコードを停止するバイトオフセット (このオフセットは含まれません)。デフォルト: buf.length
  • 戻り値: <string>

encoding で指定された文字エンコーディングに従って buf を文字列にデコードします。startend を渡して buf のサブセットのみをデコードすることができます。

encoding'utf8' で、入力のバイトシーケンスが有効な UTF-8 でない場合、無効な各バイトは置換文字 U+FFFD に置き換えられます。

文字列インスタンスの最大長 (UTF-16 コードユニット単位) は buffer.constants.MAX_STRING_LENGTH として利用可能です。

import { Buffer } from 'node:buffer';

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: téconst { Buffer } = require('node:buffer');

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té

buf.values()#

buf の値 (バイト) の イテレータ を作成して返します。この関数は、Bufferfor..of 文で使用されるときに自動的に呼び出されます。

import { Buffer } from 'node:buffer';

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

for (const value of buf.values()) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114

for (const value of buf) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114const { Buffer } = require('node:buffer');

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

for (const value of buf.values()) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114

for (const value of buf) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114

buf.write(string[, offset[, length]][, encoding])#

  • string <string> buf に書き込む文字列。
  • offset <integer> string の書き込みを開始する前にスキップするバイト数。デフォルト: 0
  • length <integer> 書き込む最大バイト数 (書き込まれるバイトは buf.length - offset を超えません)。デフォルト: buf.length - offset
  • encoding <string> string の文字エンコーディング。デフォルト: 'utf8'
  • 戻り値: <integer> 書き込まれたバイト数。

encoding の文字エンコーディングに従って、offset の位置に stringbuf に書き込みます。length パラメータは書き込むバイト数です。buf に文字列全体を収めるのに十分なスペースがない場合、string の一部のみが書き込まれます。ただし、部分的にエンコードされた文字は書き込まれません。

import { Buffer } from 'node:buffer';

const buf = Buffer.alloc(256);

const len = buf.write('\u00bd + \u00bc = \u00be', 0);

console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : abconst { Buffer } = require('node:buffer');

const buf = Buffer.alloc(256);

const len = buf.write('\u00bd + \u00bc = \u00be', 0);

console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab

buf.writeBigInt64BE(value[, offset])#

  • value <bigint> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeBigInt64BE(0x0102030405060708n, 0);

console.log(buf);
// Prints: <Buffer 01 02 03 04 05 06 07 08>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeBigInt64BE(0x0102030405060708n, 0);

console.log(buf);
// Prints: <Buffer 01 02 03 04 05 06 07 08>

buf.writeBigInt64LE(value[, offset])#

  • value <bigint> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeBigInt64LE(0x0102030405060708n, 0);

console.log(buf);
// Prints: <Buffer 08 07 06 05 04 03 02 01>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeBigInt64LE(0x0102030405060708n, 0);

console.log(buf);
// Prints: <Buffer 08 07 06 05 04 03 02 01>

buf.writeBigUInt64BE(value[, offset])#

  • value <bigint> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。

この関数は writeBigUint64BE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeBigUInt64BE(0xdecafafecacefaden, 0);

console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeBigUInt64BE(0xdecafafecacefaden, 0);

console.log(buf);
// Prints: <Buffer de ca fa fe ca ce fa de>

buf.writeBigUInt64LE(value[, offset])#

  • value <bigint> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeBigUInt64LE(0xdecafafecacefaden, 0);

console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeBigUInt64LE(0xdecafafecacefaden, 0);

console.log(buf);
// Prints: <Buffer de fa ce ca fe fa ca de>

この関数は writeBigUint64LE エイリアスでも利用できます。

buf.writeDoubleBE(value[, offset])#

  • value <number> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value は JavaScript の数値である必要があります。value が JavaScript の数値以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeDoubleBE(123.456, 0);

console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeDoubleBE(123.456, 0);

console.log(buf);
// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>

buf.writeDoubleLE(value[, offset])#

  • value <number> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 8 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value は JavaScript の数値である必要があります。value が JavaScript の数値以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(8);

buf.writeDoubleLE(123.456, 0);

console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(8);

buf.writeDoubleLE(123.456, 0);

console.log(buf);
// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>

buf.writeFloatBE(value[, offset])#

  • value <number> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value が JavaScript の数値以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeFloatBE(0xcafebabe, 0);

console.log(buf);
// Prints: <Buffer 4f 4a fe bb>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeFloatBE(0xcafebabe, 0);

console.log(buf);
// Prints: <Buffer 4f 4a fe bb>

buf.writeFloatLE(value[, offset])#

  • value <number> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value が JavaScript の数値以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeFloatLE(0xcafebabe, 0);

console.log(buf);
// Prints: <Buffer bb fe 4a 4f>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeFloatLE(0xcafebabe, 0);

console.log(buf);
// Prints: <Buffer bb fe 4a 4f>

buf.writeInt8(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 1 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue を書き込みます。value は有効な符号付き 8 ビット整数でなければなりません。value が符号付き 8 ビット整数以外の場合、動作は未定義です。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(2);

buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);

console.log(buf);
// Prints: <Buffer 02 fe>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(2);

buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);

console.log(buf);
// Prints: <Buffer 02 fe>

buf.writeInt16BE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value は有効な符号付き 16 ビット整数でなければなりません。value が符号付き 16 ビット整数以外の場合、動作は未定義です。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(2);

buf.writeInt16BE(0x0102, 0);

console.log(buf);
// Prints: <Buffer 01 02>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(2);

buf.writeInt16BE(0x0102, 0);

console.log(buf);
// Prints: <Buffer 01 02>

buf.writeInt16LE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value は有効な符号付き 16 ビット整数でなければなりません。value が符号付き 16 ビット整数以外の場合、動作は未定義です。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(2);

buf.writeInt16LE(0x0304, 0);

console.log(buf);
// Prints: <Buffer 04 03>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(2);

buf.writeInt16LE(0x0304, 0);

console.log(buf);
// Prints: <Buffer 04 03>

buf.writeInt32BE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value は有効な符号付き 32 ビット整数でなければなりません。value が符号付き 32 ビット整数以外の場合、動作は未定義です。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeInt32BE(0x01020304, 0);

console.log(buf);
// Prints: <Buffer 01 02 03 04>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeInt32BE(0x01020304, 0);

console.log(buf);
// Prints: <Buffer 01 02 03 04>

buf.writeInt32LE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value は有効な符号付き 32 ビット整数でなければなりません。value が符号付き 32 ビット整数以外の場合、動作は未定義です。

value は 2 の補数符号付き整数として解釈および書き込まれます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeInt32LE(0x05060708, 0);

console.log(buf);
// Prints: <Buffer 08 07 06 05>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeInt32LE(0x05060708, 0);

console.log(buf);
// Prints: <Buffer 08 07 06 05>

buf.writeIntBE(value, offset, byteLength)#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 書き込むバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvaluebyteLength バイト分、ビッグエンディアンで書き込みます。最大 48 ビットの精度をサポートします。value が符号付き整数以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(6);

buf.writeIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(6);

buf.writeIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>

buf.writeIntLE(value, offset, byteLength)#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 書き込むバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvaluebyteLength バイト分、リトルエンディアンで書き込みます。最大 48 ビットの精度をサポートします。value が符号付き整数以外の場合、動作は未定義です。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(6);

buf.writeIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(6);

buf.writeIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>

buf.writeUInt8(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 1 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue を書き込みます。value は有効な符号なし 8 ビット整数でなければなりません。value が符号なし 8 ビット整数以外の場合、動作は未定義です。

この関数は writeUint8 エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);

console.log(buf);
// Prints: <Buffer 03 04 23 42>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);

console.log(buf);
// Prints: <Buffer 03 04 23 42>

buf.writeUInt16BE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value は有効な符号なし 16 ビット整数でなければなりません。value が符号なし 16 ビット整数以外の場合、動作は未定義です。

この関数は writeUint16BE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);

console.log(buf);
// Prints: <Buffer de ad be ef>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);

console.log(buf);
// Prints: <Buffer de ad be ef>

buf.writeUInt16LE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 2 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value は有効な符号なし 16 ビット整数でなければなりません。value が符号なし 16 ビット整数以外の場合、動作は未定義です。

この関数は writeUint16LE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);

console.log(buf);
// Prints: <Buffer ad de ef be>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);

console.log(buf);
// Prints: <Buffer ad de ef be>

buf.writeUInt32BE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をビッグエンディアンで書き込みます。value は有効な符号なし 32 ビット整数でなければなりません。value が符号なし 32 ビット整数以外の場合、動作は未定義です。

この関数は writeUint32BE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeUInt32BE(0xfeedface, 0);

console.log(buf);
// Prints: <Buffer fe ed fa ce>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeUInt32BE(0xfeedface, 0);

console.log(buf);
// Prints: <Buffer fe ed fa ce>

buf.writeUInt32LE(value[, offset])#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - 4 を満たす必要があります。デフォルト: 0
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvalue をリトルエンディアンで書き込みます。value は有効な符号なし 32 ビット整数でなければなりません。value が符号なし 32 ビット整数以外の場合、動作は未定義です。

この関数は writeUint32LE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(4);

buf.writeUInt32LE(0xfeedface, 0);

console.log(buf);
// Prints: <Buffer ce fa ed fe>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(4);

buf.writeUInt32LE(0xfeedface, 0);

console.log(buf);
// Prints: <Buffer ce fa ed fe>

buf.writeUIntBE(value, offset, byteLength)#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 書き込むバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvaluebyteLength バイト分、ビッグエンディアンで書き込みます。最大 48 ビットの精度をサポートします。value が符号なし整数以外の場合、動作は未定義です。

この関数は writeUintBE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(6);

buf.writeUIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(6);

buf.writeUIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>

buf.writeUIntLE(value, offset, byteLength)#

  • value <integer> buf に書き込まれる数値。
  • offset <integer> 書き込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength を満たす必要があります。
  • byteLength <integer> 書き込むバイト数。0 < byteLength <= 6 を満たす必要があります。
  • 戻り値: <integer> offset に書き込まれたバイト数を加えた値。

指定された offsetbufvaluebyteLength バイト分、リトルエンディアンで書き込みます。最大 48 ビットの精度をサポートします。value が符号なし整数以外の場合、動作は未定義です。

この関数は writeUintLE エイリアスでも利用できます。

import { Buffer } from 'node:buffer';

const buf = Buffer.allocUnsafe(6);

buf.writeUIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>const { Buffer } = require('node:buffer');

const buf = Buffer.allocUnsafe(6);

buf.writeUIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: <Buffer ab 90 78 56 34 12>

new Buffer(array)#

安定性: 0 - 非推奨: 代わりに Buffer.from(array) を使用してください。

Buffer.from(array) を参照してください。

new Buffer(arrayBuffer[, byteOffset[, length]])#

安定性: 0 - 非推奨: 代わりに Buffer.from(arrayBuffer[, byteOffset[, length]]) を使用してください。

Buffer.from(arrayBuffer[, byteOffset[, length]]) を参照してください。

new Buffer(buffer)#

安定性: 0 - 非推奨: 代わりに Buffer.from(buffer) を使用してください。

Buffer.from(buffer) を参照してください。

new Buffer(size)#

安定性: 0 - 非推奨: 代わりに Buffer.alloc() を使用してください (Buffer.allocUnsafe() も参照)。

  • size <integer> 新しいBufferの希望する長さ。

Buffer.alloc()Buffer.allocUnsafe() を参照してください。このコンストラクタのバリアントは Buffer.alloc() と同等です。

new Buffer(string[, encoding])#

安定性: 0 - 非推奨: 代わりに Buffer.from(string[, encoding]) を使用してください。

  • string <string> エンコードする文字列。
  • encoding <string> stringのエンコーディング。デフォルト: 'utf8'

Buffer.from(string[, encoding]) を参照してください。

クラス: File#

<File> はファイルに関する情報を提供します。

new buffer.File(sources, fileName[, options])#

file.name#

File の名前。

file.lastModified#

File の最終更新日時。

node:buffer モジュール API#

Buffer オブジェクトはグローバルとして利用可能ですが、require('node:buffer') を使用してアクセスする node:buffer モジュールを介してのみ利用可能な追加の Buffer 関連 API があります。

buffer.atob(data)#

安定性: 3 - レガシー。代わりに Buffer.from(data, 'base64') を使用してください。

  • data <any> Base64 エンコードされた入力文字列。

Base64 エンコードされたデータの文字列をバイトにデコードし、それらのバイトを Latin-1 (ISO-8859-1) を使用して文字列にエンコードします。

data は文字列に強制変換できる任意の JavaScript 値にすることができます。

この関数は、レガシーなウェブプラットフォーム API との互換性のためだけに提供されており、新しいコードでは決して使用すべきではありません。なぜなら、それらはバイナリデータを表現するために文字列を使用し、JavaScript に型付き配列が導入される以前のものであるためです。Node.js API を使用して実行されるコードでは、base64 エンコードされた文字列とバイナリデータ間の変換は Buffer.from(str, 'base64')buf.toString('base64') を使用して実行する必要があります。

buffer.btoa(data)#

安定性: 3 - レガシー。代わりに buf.toString('base64') を使用してください。

  • data <any> ASCII (Latin1) 文字列。

文字列を Latin-1 (ISO-8859) を使用してバイトにデコードし、それらのバイトを Base64 を使用して文字列にエンコードします。

data は文字列に強制変換できる任意の JavaScript 値にすることができます。

この関数は、レガシーなウェブプラットフォーム API との互換性のためだけに提供されており、新しいコードでは決して使用すべきではありません。なぜなら、それらはバイナリデータを表現するために文字列を使用し、JavaScript に型付き配列が導入される以前のものであるためです。Node.js API を使用して実行されるコードでは、base64 エンコードされた文字列とバイナリデータ間の変換は Buffer.from(str, 'base64')buf.toString('base64') を使用して実行する必要があります。

buffer.isAscii(input)#

この関数は、input が空の場合を含め、input が有効な ASCII エンコードデータのみを含む場合に true を返します。

input がデタッチされた array buffer の場合、スローします。

buffer.isUtf8(input)#

この関数は、input が空の場合を含め、input が有効な UTF-8 エンコードデータのみを含む場合に true を返します。

input がデタッチされた array buffer の場合、スローします。

buffer.INSPECT_MAX_BYTES#

buf.inspect() が呼び出されたときに返される最大バイト数を返します。これはユーザーモジュールによって上書きできます。buf.inspect() の動作の詳細については、util.inspect() を参照してください。

buffer.kMaxLength#

  • 型: <integer> 単一の Buffer インスタンスに許容される最大サイズ。

buffer.constants.MAX_LENGTH のエイリアスです。

buffer.kStringMaxLength#

  • 型: <integer> 単一の string インスタンスに許容される最大長。

buffer.constants.MAX_STRING_LENGTH のエイリアスです。

buffer.resolveObjectURL(id)#

  • id <string> 以前の URL.createObjectURL() の呼び出しによって返された 'blob:nodedata:...' URL 文字列。
  • 戻り値: <Blob>

'blob:nodedata:...' を、以前の URL.createObjectURL() の呼び出しで登録された関連する <Blob> オブジェクトに解決します。

buffer.transcode(source, fromEnc, toEnc)#

指定された Buffer または Uint8Array インスタンスを、ある文字エンコーディングから別の文字エンコーディングに再エンコードします。新しい Buffer インスタンスを返します。

fromEnc または toEnc が無効な文字エンコーディングを指定した場合、または fromEnc から toEnc への変換が許可されていない場合にスローします。

buffer.transcode() でサポートされているエンコーディングは、'ascii''utf8''utf16le''ucs2''latin1'、および 'binary' です。

指定されたバイトシーケンスがターゲットエンコーディングで適切に表現できない場合、トランスコーディングプロセスは代替文字を使用します。例えば、

import { Buffer, transcode } from 'node:buffer';

const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'const { Buffer, transcode } = require('node:buffer');

const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'

ユーロ () 記号は US-ASCII で表現できないため、トランスコードされた Buffer では ? に置き換えられます。

Buffer の定数#

buffer.constants.MAX_LENGTH#
  • 型: <integer> 単一の Buffer インスタンスに許容される最大サイズ。

32 ビットアーキテクチャでは、この値は現在 230 - 1 (約 1 GiB) です。

64 ビットアーキテクチャでは、この値は現在 253 - 1 (約 8 PiB) です。

これは内部的に v8::TypedArray::kMaxLength を反映しています。

この値は buffer.kMaxLength としても利用可能です。

buffer.constants.MAX_STRING_LENGTH#
  • 型: <integer> 単一の string インスタンスに許容される最大長。

string プリミティブが持つことができる最大の length を UTF-16 コードユニットで数えたものを表します。

この値は、使用されている JS エンジンによって異なる場合があります。

Buffer.from()Buffer.alloc()、および Buffer.allocUnsafe()#

Node.js の 6.0.0 より前のバージョンでは、Buffer インスタンスは Buffer コンストラクタ関数を使用して作成されていました。これは、提供される引数に基づいて返される Buffer を異なる方法で割り当てます。

  • Buffer() の最初の引数として数値を渡す (例: new Buffer(10)) と、指定されたサイズの新しい Buffer オブジェクトが割り当てられます。Node.js 8.0.0 より前では、このような Buffer インスタンスに割り当てられたメモリは初期化されておらず、機密データを含む可能性がありました。このような Buffer インスタンスは、Buffer からデータを読み取る前に、buf.fill(0) を使用するか、Buffer 全体に書き込むことによって、後で初期化しなければなりませんでした。この動作はパフォーマンスを向上させるために意図的なものですが、開発経験から、高速だが初期化されていない Buffer を作成することと、低速だがより安全な Buffer を作成することの間で、より明確な区別が必要であることが示されました。Node.js 8.0.0 以降、Buffer(num)new Buffer(num) は初期化されたメモリを持つ Buffer を返します。
  • 最初の引数として文字列、配列、または Buffer を渡すと、渡されたオブジェクトのデータが Buffer にコピーされます。
  • <ArrayBuffer> または <SharedArrayBuffer> を渡すと、指定されたアレイバッファと割り当てられたメモリを共有する Buffer が返されます。

new Buffer() の動作は最初の引数の型によって異なるため、引数の検証や Buffer の初期化が行われない場合、アプリケーションにセキュリティや信頼性の問題が意図せず導入される可能性があります。

例えば、攻撃者がアプリケーションに文字列が期待される場所で数値を受け取らせることができた場合、アプリケーションは new Buffer("100") の代わりに new Buffer(100) を呼び出す可能性があり、コンテンツ "100" を持つ 3 バイトのバッファを割り当てる代わりに 100 バイトのバッファを割り当てることになります。これは一般的に JSON API 呼び出しで可能です。JSON は数値型と文字列型を区別するため、入力を十分に検証しない単純なアプリケーションが常に文字列を受け取ると期待するかもしれない場所に、数値を注入することを可能にします。Node.js 8.0.0 より前では、100 バイトのバッファには任意の既存のメモリ内データが含まれている可能性があり、メモリ内の機密情報をリモートの攻撃者に漏洩させるために使用される可能性がありました。Node.js 8.0.0 以降はデータがゼロフィルされるため、メモリの漏洩は発生しません。しかし、サーバーに非常に大きなバッファを割り当てさせ、パフォーマンスの低下やメモリ枯渇によるクラッシュを引き起こすなど、他の攻撃は依然として可能です。

Buffer インスタンスの作成をより信頼性が高く、エラーが発生しにくいものにするために、new Buffer() コンストラクタのさまざまな形式は非推奨となり、個別の Buffer.from()Buffer.alloc()、および Buffer.allocUnsafe() メソッドに置き換えられました。

開発者は、new Buffer() コンストラクタの既存のすべての使用を、これらの新しい API のいずれかに移行する必要があります。

  • Buffer.from(array) は、提供されたオクテットのコピーを含む新しい Buffer を返します。
  • Buffer.from(arrayBuffer[, byteOffset[, length]]) は、指定された <ArrayBuffer>同じ割り当てメモリを共有する新しい Buffer を返します。
  • Buffer.from(buffer) は、指定された Buffer の内容のコピーを含む新しい Buffer を返します。
  • Buffer.from(string[, encoding]) は、提供された文字列のコピーを含む新しい Buffer を返します。
  • Buffer.alloc(size[, fill[, encoding]]) は、指定されたサイズの新しい初期化済み Buffer を返します。このメソッドは Buffer.allocUnsafe(size) よりも低速ですが、新しく作成された Buffer インスタンスが機密性の高い可能性のある古いデータを含まないことを保証します。size が数値でない場合、TypeError がスローされます。
  • Buffer.allocUnsafe(size)Buffer.allocUnsafeSlow(size) はそれぞれ、指定された size の新しい初期化されていない Buffer を返します。Buffer は初期化されていないため、割り当てられたメモリセグメントには機密性の高い可能性のある古いデータが含まれている可能性があります。

Buffer.allocUnsafe()Buffer.from(string)Buffer.concat()、および Buffer.from(array) によって返される Buffer インスタンスは、sizeBuffer.poolSize の半分以下の場合、共有の内部メモリプールから割り当てられる場合がありますBuffer.allocUnsafeSlow() によって返されるインスタンスは、共有の内部メモリプールを決して使用しません。

--zero-fill-buffers コマンドラインオプション#

Node.js は --zero-fill-buffers コマンドラインオプションを使用して起動でき、これにより、新しく割り当てられたすべての Buffer インスタンスがデフォルトで作成時にゼロフィルされるようになります。このオプションがない場合、Buffer.allocUnsafe()Buffer.allocUnsafeSlow() で作成されたバッファはゼロフィルされません。このフラグの使用は、パフォーマンスに測定可能な悪影響を与える可能性があります。--zero-fill-buffers オプションは、新しく割り当てられた Buffer インスタンスが機密性の高い可能性のある古いデータを含まないことを強制する必要がある場合にのみ使用してください。

$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
<Buffer 00 00 00 00 00> 

Buffer.allocUnsafe()Buffer.allocUnsafeSlow() が「安全でない」のはなぜか?#

Buffer.allocUnsafe() および Buffer.allocUnsafeSlow() を呼び出すと、割り当てられたメモリのセグメントは初期化されません(ゼロで埋められません)。この設計によりメモリの割り当ては非常に高速になりますが、割り当てられたメモリのセグメントには機密性の高い可能性のある古いデータが含まれている可能性があります。Buffer.allocUnsafe() によって作成された Buffer をメモリを完全に上書きせずに使用すると、Buffer のメモリが読み取られたときにこの古いデータが漏洩する可能性があります。

Buffer.allocUnsafe() を使用することには明らかなパフォーマンス上の利点がありますが、アプリケーションにセキュリティ上の脆弱性を導入しないように、特別な注意を払う必要があります