Node.js v21.7.2 ドキュメント
- Node.js v21.7.2
-
► 目次
- バッファ
- バッファと文字エンコーディング
- バッファとTypedArray
- バッファとイテレーション
- クラス: `Blob`
- クラス: `Buffer`
- 静的メソッド: `Buffer.alloc(size[, fill[, encoding]])`
- 静的メソッド: `Buffer.allocUnsafe(size)`
- 静的メソッド: `Buffer.allocUnsafeSlow(size)`
- 静的メソッド: `Buffer.byteLength(string[, encoding])`
- 静的メソッド: `Buffer.compare(buf1, buf2)`
- 静的メソッド: `Buffer.concat(list[, totalLength])`
- 静的メソッド: `Buffer.copyBytesFrom(view[, offset[, length]])`
- 静的メソッド: `Buffer.from(array)`
- 静的メソッド: `Buffer.from(arrayBuffer[, byteOffset[, length]])`
- 静的メソッド: `Buffer.from(buffer)`
- 静的メソッド: `Buffer.from(object[, offsetOrEncoding[, length]])`
- 静的メソッド: `Buffer.from(string[, encoding])`
- 静的メソッド: `Buffer.isBuffer(obj)`
- 静的メソッド: `Buffer.isEncoding(encoding)`
- クラスプロパティ: `Buffer.poolSize`
buf[index]
buf.buffer
buf.byteOffset
buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])
buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
buf.entries()
buf.equals(otherBuffer)
buf.fill(value[, offset[, end]][, encoding])
buf.includes(value[, byteOffset][, encoding])
buf.indexOf(value[, byteOffset][, encoding])
buf.keys()
buf.lastIndexOf(value[, byteOffset][, encoding])
buf.length
buf.parent
buf.readBigInt64BE([offset])
buf.readBigInt64LE([offset])
buf.readBigUInt64BE([offset])
buf.readBigUInt64LE([offset])
buf.readDoubleBE([offset])
buf.readDoubleLE([offset])
buf.readFloatBE([offset])
buf.readFloatLE([offset])
buf.readInt8([offset])
buf.readInt16BE([offset])
buf.readInt16LE([offset])
buf.readInt32BE([offset])
buf.readInt32LE([offset])
buf.readIntBE(offset, byteLength)
buf.readIntLE(offset, byteLength)
buf.readUInt8([offset])
buf.readUInt16BE([offset])
buf.readUInt16LE([offset])
buf.readUInt32BE([offset])
buf.readUInt32LE([offset])
buf.readUIntBE(offset, byteLength)
buf.readUIntLE(offset, byteLength)
buf.subarray([start[, end]])
buf.slice([start[, end]])
buf.swap16()
buf.swap32()
buf.swap64()
buf.toJSON()
buf.toString([encoding[, start[, end]]])
buf.values()
buf.write(string[, offset[, length]][, encoding])
buf.writeBigInt64BE(value[, offset])
buf.writeBigInt64LE(value[, offset])
buf.writeBigUInt64BE(value[, offset])
buf.writeBigUInt64LE(value[, offset])
buf.writeDoubleBE(value[, offset])
buf.writeDoubleLE(value[, offset])
buf.writeFloatBE(value[, offset])
buf.writeFloatLE(value[, offset])
buf.writeInt8(value[, offset])
buf.writeInt16BE(value[, offset])
buf.writeInt16LE(value[, offset])
buf.writeInt32BE(value[, offset])
buf.writeInt32LE(value[, offset])
buf.writeIntBE(value, offset, byteLength)
buf.writeIntLE(value, offset, byteLength)
buf.writeUInt8(value[, offset])
buf.writeUInt16BE(value[, offset])
buf.writeUInt16LE(value[, offset])
buf.writeUInt32BE(value[, offset])
buf.writeUInt32LE(value[, offset])
buf.writeUIntBE(value, offset, byteLength)
buf.writeUIntLE(value, offset, byteLength)
new Buffer(array)
new Buffer(arrayBuffer[, byteOffset[, length]])
new Buffer(buffer)
new Buffer(size)
new Buffer(string[, encoding])
- クラス: `File`
- `node:buffer` モジュール API
- `Buffer.from()`、`Buffer.alloc()`、および `Buffer.allocUnsafe()`
- バッファ
-
► インデックス
- アサーションテスト
- 非同期コンテキストトラッキング
- 非同期フック
- バッファ
- C++ アドオン
- Node-API を使用した C/C++ アドオン
- C++ エンベッダー API
- 子プロセス
- クラスタ
- コマンドラインオプション
- コンソール
- Corepack
- 暗号化
- デバッガ
- 非推奨の API
- 診断チャネル
- DNS
- ドメイン
- エラー
- イベント
- ファイルシステム
- グローバルオブジェクト
- HTTP
- HTTP/2
- HTTPS
- インスペクタ
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール: `node:module` API
- モジュール: パッケージ
- ネットワーク
- OS
- パス
- パフォーマンスフック
- パーミッション
- プロセス
- Punnycode
- クエリ文字列
- Readline
- REPL
- レポート
- 単一実行可能アプリケーション
- ストリーム
- 文字列デコーダ
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/データグラム
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカー スレッド
- Zlib
- ► その他のバージョン
- ► オプション
バッファ#
ソースコード: 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`と文字列間の変換では、文字エンコーディングを指定できます。文字エンコーディングが指定されていない場合、デフォルトで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文字のみをサポートしています。各文字は1バイトを使用してエンコードされます。この範囲に収まらない文字は切り捨てられ、その範囲内の文字にマッピングされます。
上記のいずれかを使用して`Buffer`を文字列に変換することをデコードといい、文字列を`Buffer`に変換することをエンコードといいます。
Node.jsは、次のバイナリからテキストへのエンコーディングもサポートしています。バイナリからテキストへのエンコーディングでは、命名規則が逆になります。`Buffer`を文字列に変換することを通常エンコードといい、文字列を`Buffer`に変換することをデコードといいます。
-
`'base64'`:Base64エンコーディング。文字列から`Buffer`を作成する場合、このエンコーディングはRFC 4648、セクション5で指定されている「URLおよびファイル名セーフアルファベット」も正しく受け入れます。Base64エンコード文字列に含まれるスペース、タブ、改行などの空白文字は無視されます。
-
`'base64url'`:base64urlエンコーディング(RFC 4648、セクション5で指定)。文字列から`Buffer`を作成する場合、このエンコーディングは通常のbase64エンコード文字列も正しく受け入れます。`Buffer`を文字列にエンコードする場合、このエンコーディングはパディングを省略します。
-
`'hex'`:各バイトを2つの16進文字としてエンコードします。16進文字の偶数でない文字列をデコードすると、データの切り捨てが発生することがあります。例については以下を参照してください。
次のレガシー文字エンコーディングもサポートされています。
-
`'ascii'`:7ビットASCIIデータのみ用。文字列を`Buffer`にエンコードする場合、これは`'latin1'`を使用することと同等です。`Buffer`を文字列にデコードする場合、このエンコーディングを使用すると、デコードする前に各バイトの最上位ビットが追加でクリアされます。一般的に、`'utf8'`(または、データが常にASCIIのみであることがわかっている場合は`'latin1'`)はASCIIのみのテキストをエンコードまたはデコードする場合、より良い選択肢となるため、このエンコーディングを使用する理由はほとんどありません。レガシー互換性のためにのみ提供されています。
-
'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()
のような操作を行う場合、返された文字セットが WHATWG 仕様にリストされているものの1つであると、サーバーが実際には 'win-1252'
エンコードのデータを返し、'latin1'
エンコーディングを使用すると文字が正しくデコードされない可能性があることを意味します。
バッファと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つの方法があります。
TypedArray
コンストラクタにBuffer
を渡すと、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 ]
Buffer
の基盤となるArrayBuffer
を渡すと、Buffer
とメモリを共有するTypedArray
が作成されます。
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
を作成する際、byteOffset
と length
パラメータを渡すことで、基盤となる ArrayBuffer
の一部のみを使用できます。
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length);
// Prints: 16
const { 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引数を受け入れます。
TypedArray.from(source[, mapFn[, thisArg]])
しかし、Buffer.from()
メソッドは、マッピング関数の使用をサポートしていません。
バッファと反復処理#
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
// 3
const { 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
内に格納される文字列、<ArrayBuffer>、<TypedArray>、<DataView>、または <Blob> オブジェクト、またはこれらのオブジェクトの任意の組み合わせの配列です。options
<Object>
与えられたソースの連結を含む新しい Blob
オブジェクトを作成します。
<ArrayBuffer>、<TypedArray>、<DataView>、および <Buffer> ソースは 'Blob' にコピーされるため、'Blob' が作成された後も安全に変更できます。
文字列ソースは UTF-8 バイトシーケンスとしてエンコードされ、Blob にコピーされます。各文字列部分内の不一致のサロゲートペアは、Unicode U+FFFD 置換文字に置き換えられます。
blob.arrayBuffer()
#
- 戻り値: <Promise>
Blob
データのコピーを含む <ArrayBuffer> で解決される Promise を返します。
blob.size
#
バイト単位の Blob
の合計サイズです。
blob.slice([start[, end[, type]]])
#
この Blob
オブジェクトのデータのサブセットを含む新しい Blob
を作成して返します。元の Blob
は変更されません。
blob.stream()
#
- 戻り値: <ReadableStream>
Blob
のコンテンツを読み取ることができる新しい ReadableStream
を返します。
blob.text()
#
- 戻り値: <Promise>
UTF-8 文字列としてデコードされた Blob
の内容で解決される Promise を返します。
blob.type
#
- 型: <string>
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
<integer> 新しいBuffer
の目的の長さ。fill
<string> | <Buffer> | <Uint8Array> | <integer> 新しいBuffer
を事前に埋める値。**デフォルト:**0
。encoding
<string>fill
が文字列の場合、そのエンコーディングです。**デフォルト:**'utf8'
。
size
バイトの新しいBuffer
を割り当てます。fill
がundefined
の場合、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>
size
がbuffer.constants.MAX_LENGTH
より大きいか、0より小さい場合、ERR_OUT_OF_RANGE
がスローされます。
fill
が指定されている場合、割り当てられたBuffer
はbuf.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>
fill
とencoding
の両方が指定されている場合、割り当てられたBuffer
はbuf.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
<integer> 新しいBuffer
の目的の長さ。
size
バイトの新しいBuffer
を割り当てます。size
がbuffer.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.allocUnsafe()
、Buffer.from(array)
、およびBuffer.concat()
を使用して作成された新しいBuffer
インスタンスの高速な割り当てに使用されるプールとして、サイズBuffer.poolSize
の内部Buffer
インスタンスを事前に割り当てます。これは、size
がBuffer.poolSize >>> 1
(Buffer.poolSize
の2で割った商)より小さい場合のみです。
この事前に割り当てられた内部メモリプールの使用は、Buffer.alloc(size, fill)
とBuffer.allocUnsafe(size).fill(fill)
の呼び出し間の重要な違いです。具体的には、Buffer.alloc(size, fill)
は決して内部Buffer
プールを使用せず、Buffer.allocUnsafe(size).fill(fill)
は、size
がBuffer.poolSize
の半分以下の場合、内部Buffer
プールを使用します。この違いは微妙ですが、アプリケーションがBuffer.allocUnsafe()
が提供する追加のパフォーマンスを必要とする場合、重要になる可能性があります。
静的メソッド: Buffer.allocUnsafeSlow(size)
#
size
<integer> 新しいBuffer
の目的の長さ。
size
バイトの新しいBuffer
を割り当てます。size
がbuffer.constants.MAX_LENGTH
より大きいか、0より小さい場合、ERR_OUT_OF_RANGE
がスローされます。size
が0の場合、長さ0のBuffer
が作成されます。
このようにして作成されたBuffer
インスタンスの基礎となるメモリは、初期化されません。新しく作成されたBuffer
の内容は不明であり、機密データが含まれている可能性があります。このようなBuffer
インスタンスをゼロで初期化するには、buf.fill(0)
を使用してください。
Buffer.allocUnsafe()
を使用して新しいBuffer
インスタンスを割り当てる場合、4 KiB未満の割り当ては、単一の事前に割り当てられた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])
#
string
<string> | <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> | <SharedArrayBuffer> 長さを計算する値。encoding
<string>string
が文字列の場合、そのエンコーディングです。デフォルト:'utf8'
。- 戻り値: <integer>
string
に含まれるバイト数。
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 bytes
const { 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)
#
buf1
<Buffer> | <Uint8Array>buf2
<Buffer> | <Uint8Array>- 戻り値: <integer> 比較の結果に応じて、
-1
、0
、または1
のいずれか。詳細はbuf.compare()
を参照してください。
buf1
とbuf2
を比較します。通常は、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[]> | <Uint8Array[]> 結合するBuffer
またはUint8Array
インスタンスのリスト。totalLength
<integer>list
内のBuffer
インスタンスを連結したときの合計長さ。- 戻り値: <Buffer>
list
内のすべてのBuffer
インスタンスを連結した結果である新しいBuffer
を返します。
リストにアイテムがない場合、またはtotalLength
が0の場合、長さ0の新しいBuffer
が返されます。
totalLength
が指定されていない場合、list
内のBuffer
インスタンスの長さを合計して計算されます。
totalLength
が指定されている場合、符号なし整数に変換されます。list
内のBuffer
の合計長さがtotalLength
を超える場合、結果は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: 42
const { 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
<TypedArray> コピーする<TypedArray>。offset
<integer>view
内の開始オフセット。デフォルト:0
。length
<integer> コピーするview
の要素数。デフォルト:view.length - offset
。
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)
#
array
<integer[]>
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]);
array
が配列のようなオブジェクト(つまり、数値型のlength
プロパティを持つオブジェクト)の場合、それがBuffer
またはUint8Array
でない限り、配列として扱われます。これは、他のすべてのTypedArray
変種が配列として扱われることを意味します。TypedArray
を裏付けるバイトからBuffer
を作成するには、Buffer.copyBytesFrom()
を使用してください。
array
がArray
またはBuffer.from()
のバリアントに適した他の型でない場合、TypeError
がスローされます。
Buffer.from(array)
および Buffer.from(string)
は、Buffer.allocUnsafe()
と同様に、内部の Buffer
プールを使用する場合があります。
静的メソッド: Buffer.from(arrayBuffer[, byteOffset[, length]])
#
arrayBuffer
<ArrayBuffer> | <SharedArrayBuffer>ArrayBuffer
、SharedArrayBuffer
(例:TypedArray
の.buffer
プロパティ)。byteOffset
<整数> 公開する最初のバイトのインデックス。デフォルト:0
。length
<整数> 公開するバイト数。デフォルト:arrayBuffer.byteLength - byteOffset
。
これは、基となるメモリをコピーせずに、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>
オプションの byteOffset
および length
引数は、Buffer
が共有する arrayBuffer
内のメモリ範囲を指定します。
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
const { 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
がスローされます。
基となる ArrayBuffer
は、TypedArray
ビューの範囲を超えるメモリ範囲をカバーできることに注意することが重要です。TypedArray
の buffer
プロパティを使用して作成された新しい 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> | <Uint8Array> データをコピーする既存のBuffer
またはUint8Array
。
渡された 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: buffer
const { 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
buffer
が Buffer
または Buffer.from()
のバリアントに適した別の型でない場合、TypeError
がスローされます。
静的メソッド: Buffer.from(object[, offsetOrEncoding[, length]])
#
object
<Object>Symbol.toPrimitive
またはvalueOf()
をサポートするオブジェクト。offsetOrEncoding
<整数> | <文字列> バイトオフセットまたはエンコーディング。length
<整数> 長さ。
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
を含む新しい 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ést
const { 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.isBuffer(obj)
#
obj
が Buffer
の場合 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)); // false
const { 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
がサポートされている文字エンコーディングの名前の場合 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: false
const { 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
#
- <整数> デフォルト:
8192
これは、プールに使用される事前に割り当てられた内部 Buffer
インスタンスのサイズ(バイト単位)です。この値は変更できます。
buf[index]
#
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.js
const { 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: true
const { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
buf.byteOffset
#
- <整数>
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
<整数> 比較を開始するtarget
内のオフセット。デフォルト:0
。targetEnd
<整数> 比較を終了するtarget
内のオフセット(非包含)。デフォルト:target.length
。sourceStart
<整数> 比較を開始するbuf
内のオフセット。デフォルト:0
。sourceEnd
<整数> 比較を終了するbuf
内のオフセット(非包含)。デフォルト:buf.length
。- 戻り値: <整数>
buf
と target
を比較し、ソート順序で buf
が target
より前、後、または同じかどうかを示す数値を返します。比較は、各 Buffer
の実際のバイトシーケンスに基づいています。
target
がbuf
と同じ場合、0
が返されます。target
がソート時にbuf
の*前*に来るべき場合、1
が返されます。target
がソート時にbuf
の*後*に来るべき場合、-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].)
オプションの targetStart
、targetEnd
、sourceStart
、および sourceEnd
引数を使用して、それぞれ target
と buf
内の特定の範囲への比較を制限できます。
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: 1
const { 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 < 0
、sourceStart < 0
、targetEnd > target.byteLength
、またはsourceEnd > source.byteLength
の場合、ERR_OUT_OF_RANGE
がスローされます。
buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
#
target
<Buffer> | <Uint8Array> コピー先のBuffer
またはUint8Array
。targetStart
<整数> 書き込みを開始するtarget
内のオフセット。デフォルト:0
。sourceStart
<整数> コピーを開始するbuf
内のオフセット。デフォルト:0
。sourceEnd
<整数> コピーを停止するbuf
内のオフセット(非包含)。デフォルト:buf.length
。- 戻り値: <整数> コピーされたバイト数。
target
の領域に buf
の領域からデータをコピーします。target
のメモリ領域が buf
と重なっている場合でも動作します。
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: efghijghijklmnopqrstuvwxyz
const { 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)
#
otherBuffer
<Buffer> | <Uint8Array>buf
と比較するBuffer
またはUint8Array
。- 戻り値: <ブール値>
buf
と otherBuffer
の両方に完全に同じバイトが含まれている場合は 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: false
const { 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
<文字列> | <Buffer> | <Uint8Array> | <整数>buf
を埋める値。空の値(文字列、Uint8Array、Buffer)は0
に強制変換されます。offset
<整数>buf
の埋め込みを開始する前にスキップするバイト数。デフォルト:0
。end
<整数>buf
の埋め込みを停止する場所(非包含)。デフォルト:buf.length
。encoding
<文字列>value
が文字列の場合のエンコーディング。デフォルト:'utf8'
。- 戻り値: <Buffer>
buf
への参照。
指定された value
で buf
を埋めます。offset
と end
が指定されていない場合、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進数)より大きい場合、buf
は value & 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
<文字列> | <Buffer> | <Uint8Array> | <整数> 検索対象。byteOffset
<整数>buf
内の検索を開始する場所。負の場合、オフセットはbuf
の末尾から計算されます。デフォルト:0
。encoding
<文字列>value
が文字列の場合のエンコーディング。デフォルト:'utf8'
。- 戻り値: <ブール値>
value
がbuf
内に見つかった場合は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: false
const { 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
<文字列> | <Buffer> | <Uint8Array> | <整数> 検索対象。byteOffset
<整数>buf
内の検索を開始する場所。負の場合、オフセットはbuf
の末尾から計算されます。デフォルト:0
。encoding
<文字列>value
が文字列の場合、buf
内で検索される文字列のバイナリ表現を決定するために使用されるエンコーディングです。デフォルト:'utf8'
。- 戻り値: <整数>
buf
内のvalue
の最初の出現位置のインデックス。buf
にvalue
が含まれていない場合は-1
。
value
が以下の場合:
- 文字列の場合、
value
はencoding
の文字エンコーディングに従って解釈されます。 Buffer
またはUint8Array
の場合、value
は全体として使用されます。部分的なBuffer
を比較するには、buf.subarray
を使用します。- 数値の場合、
value
は0
から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: 6
const { 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
であり、byteOffset
が buf.length
より小さい場合、byteOffset
が返されます。value
が空であり、byteOffset
が buf.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
// 5
const { 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
<文字列> | <Buffer> | <Uint8Array> | <整数> 検索対象。byteOffset
<整数>buf
内の検索を開始する場所。負の場合、オフセットはbuf
の末尾から計算されます。デフォルト:buf.length - 1
。encoding
<文字列>value
が文字列の場合、buf
内で検索される文字列のバイナリ表現を決定するために使用されるエンコーディングです。デフォルト:'utf8'
。- 戻り値: <整数>
buf
内のvalue
の最後の出現位置のインデックス。buf
にvalue
が含まれていない場合は-1
。
buf.indexOf()
と同じですが、最初の出現位置ではなく、最後の出現位置が見つかる点が異なります。
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: 4
const { 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: 1234
const { 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
#
buf.buffer
を使用してください。buf.parent
プロパティは、buf.buffer
の非推奨のエイリアスです。
buf.readBigInt64BE([offset])
#
指定された offset
で buf
から符号付きビッグエンディアン 64 ビット整数を読み取ります。
Buffer
から読み取られた整数は、2 の補数の符号付き値として解釈されます。
buf.readBigInt64LE([offset])
#
指定された offset
で buf
から符号付きリトルエンディアン 64 ビット整数を読み取ります。
Buffer
から読み取られた整数は、2 の補数の符号付き値として解釈されます。
buf.readBigUInt64BE([offset])
#
指定されたoffset
位置のbuf
から、符号なしビッグエンディアン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: 4294967295n
const { 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
位置のbuf
から、符号なしリトルエンディアン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: 18446744069414584320n
const { 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
位置のbuf
から、64ビットビッグエンディアンの倍精度浮動小数点数を読み取ります。
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-304
const { 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
位置のbuf
から、64ビットリトルエンディアンの倍精度浮動小数点数を読み取ります。
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
位置のbuf
から、32ビットビッグエンディアンの単精度浮動小数点数を読み取ります。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38
const { 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
位置のbuf
から、32ビットリトルエンディアンの単精度浮動小数点数を読み取ります。
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
位置のbuf
から、符号付き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
位置のbuf
から、符号付きビッグエンディアン16ビット整数を取得します。
Buffer
から読み取られた整数は、2 の補数の符号付き値として解釈されます。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE(0));
// Prints: 5
buf.readInt16LE([offset])
#
指定されたoffset
位置のbuf
から、符号付きリトルエンディアン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
位置のbuf
から、符号付きビッグエンディアン32ビット整数を取得します。
Buffer
から読み取られた整数は、2 の補数の符号付き値として解釈されます。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0));
// Prints: 5
buf.readInt32LE([offset])
#
指定されたoffset
位置のbuf
から、符号付きリトルエンディアン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
<整数> 読み込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength
を満たす必要があります。byteLength
<整数> 読み取るバイト数。0 < byteLength <= 6
を満たす必要があります。- 戻り値: <整数>
指定されたoffset
位置のbuf
から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
<整数> 読み込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength
を満たす必要があります。byteLength
<整数> 読み取るバイト数。0 < byteLength <= 6
を満たす必要があります。- 戻り値: <整数>
指定されたoffset
位置のbuf
から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: -546f87a9cbee
const { 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
位置のbuf
から、符号なし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
位置のbuf
から、符号なしビッグエンディアン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: 3456
const { 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
位置のbuf
から、符号なしリトルエンディアン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
位置のbuf
から、符号なしビッグエンディアン32ビット整数を取得します。
この関数は、readUint32BE
というエイリアスでも使用できます。
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678
const { 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
位置のbuf
から、符号なしリトルエンディアン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
<整数> 読み込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength
を満たす必要があります。byteLength
<整数> 読み取るバイト数。0 < byteLength <= 6
を満たす必要があります。- 戻り値: <整数>
指定されたoffset
位置のbuf
から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
<整数> 読み込みを開始する前にスキップするバイト数。0 <= offset <= buf.length - byteLength
を満たす必要があります。byteLength
<整数> 読み取るバイト数。0 < byteLength <= 6
を満たす必要があります。- 戻り値: <整数>
指定されたoffset
位置のbuf
から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: ab9078563412
const { 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
<整数> 新しいBuffer
の開始位置。 **デフォルト:**0
。end
<整数> 新しいBuffer
の終了位置(含まない)。 **デフォルト:**buf.length
.- 戻り値: <Buffer>
元のバッファと同じメモリを参照するが、start
とend
インデックスによってオフセットされ、切り詰められた新しいBuffer
を返します。
end
にbuf.length
より大きい値を指定した場合、end
にbuf.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: !bc
const { 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
<整数> 新しいBuffer
の開始位置。 **デフォルト:**0
。end
<整数> 新しいBuffer
の終了位置(含まない)。 **デフォルト:**buf.length
.- 戻り値: <Buffer>
buf.subarray
を使用してください。元のバッファと同じメモリを参照するが、start
とend
インデックスによってオフセットされ、切り詰められた新しいBuffer
を返します。
このメソッドは、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
<文字列> 使用する文字エンコーディング。 **デフォルト:**'utf8'
。start
<整数> デコードを開始するバイトオフセット。 **デフォルト:**0
。end
<整数> デコードを停止するバイトオフセット(含まない)。 **デフォルト:**buf.length
.- 戻り値: <文字列>
encoding
で指定された文字エンコーディングに従って、buf
を文字列にデコードします。start
とend
を指定することで、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
の値(バイト)に対するイテレータを作成して返します。この関数は、Buffer
がfor..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
// 114
const { 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
の位置にstring
をbuf
に書き込みます。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 : ab
const { 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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。
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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。
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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。
この関数は、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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。
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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置にvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
のbyteLength
バイトをbuf
に書き込みます。最大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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
のbyteLength
バイトをbuf
に書き込みます。最大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
と書き込まれたバイト数の合計。
指定されたoffset
の位置にvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
の位置に、ビッグエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
に、リトルエンディアンでvalue
をbuf
に書き込みます。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
と書き込まれたバイト数の合計。
指定されたoffset
に、ビッグエンディアンでvalue
のbyteLength
バイトをbuf
に書き込みます。最大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
と書き込まれたバイト数の合計。
指定されたoffset
に、リトルエンディアンでvalue
のbyteLength
バイトをbuf
に書き込みます。最大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)
#
Buffer.from(array)
を使用してください。array
<integer[]> コピー元のバイトの配列。
Buffer.from(array)
を参照してください。
new Buffer(arrayBuffer[, byteOffset[, length]])
#
Buffer.from(arrayBuffer[, byteOffset[, length]])
を使用してください。arrayBuffer
<ArrayBuffer> | <SharedArrayBuffer>ArrayBuffer
、SharedArrayBuffer
、またはTypedArray
の.buffer
プロパティ。byteOffset
<整数> 公開する最初のバイトのインデックス。デフォルト:0
。length
<整数> 公開するバイト数。デフォルト:arrayBuffer.byteLength - byteOffset
。
Buffer.from(arrayBuffer[, byteOffset[, length]])
を参照してください。
new Buffer(buffer)
#
Buffer.from(buffer)
を使用してください。buffer
<Buffer> | <Uint8Array> データをコピーする既存のBuffer
またはUint8Array
。
Buffer.from(buffer)
を参照してください。
new Buffer(size)
#
size
<integer> 新しいBuffer
の目的の長さ。
Buffer.alloc()
とBuffer.allocUnsafe()
を参照してください。このバリアントのコンストラクタはBuffer.alloc()
と同等です。
new Buffer(string[, encoding])
#
Buffer.from(string[, encoding])
を使用してください。Buffer.from(string[, encoding])
を参照してください。
クラス: File
#
- 拡張クラス: <Blob>
File
はファイルに関する情報を提供します。
new buffer.File(sources, fileName[, options])
#
sources
<string[]> | <ArrayBuffer[]> | <TypedArray[]> | <DataView[]> | <Blob[]> | <File[]>File
内に格納される文字列、<ArrayBuffer>、<TypedArray>、<DataView>、<File>、または<Blob>オブジェクト、またはこれらのオブジェクトの任意の組み合わせの配列。fileName
<string> ファイル名。options
<Object>
file.name
#
- 型: <string>
File
の名前。
file.lastModified
#
- 型: <number>
File
の最終変更日。
node:buffer
モジュールAPI#
Buffer
オブジェクトはグローバルとして利用できますが、require('node:buffer')
を使用してアクセスするnode:buffer
モジュールを介してのみ利用可能な追加のBuffer
関連APIがあります。
buffer.atob(data)
#
Buffer.from(data, 'base64')
を使用してください。data
<any> Base64でエンコードされた入力文字列。
Base64でエンコードされたデータの文字列をバイトにデコードし、それらのバイトをLatin-1(ISO-8859-1)を使用して文字列にエンコードします。
data
は、文字列に変換できる任意のJavaScript値にすることができます。
この関数は、レガシーなWebプラットフォームAPIとの互換性のためにのみ提供されており、新しいコードでは決して使用しないでください。バイナリデータを表現するために文字列を使用しており、JavaScriptに型付き配列が導入される前に存在していたためです。Node.js APIを使用するコードでは、Base64でエンコードされた文字列とバイナリデータ間の変換は、Buffer.from(str, 'base64')
とbuf.toString('base64')
を使用して実行する必要があります。
buffer.btoa(data)
#
buf.toString('base64')
を使用してください。data
<any> ASCII(Latin1)文字列。
Latin-1(ISO-8859)を使用して文字列をバイトにデコードし、それらのバイトをBase64を使用して文字列にエンコードします。
data
は、文字列に変換できる任意のJavaScript値にすることができます。
この関数は、レガシーなWebプラットフォームAPIとの互換性のためにのみ提供されており、新しいコードでは決して使用しないでください。バイナリデータを表現するために文字列を使用しており、JavaScriptに型付き配列が導入される前に存在していたためです。Node.js APIを使用するコードでは、Base64でエンコードされた文字列とバイナリデータ間の変換は、Buffer.from(str, 'base64')
とbuf.toString('base64')
を使用して実行する必要があります。
buffer.isAscii(input)
#
- input <Buffer> | <ArrayBuffer> | <TypedArray> 検証する入力。
- 戻り値: <ブール値>
この関数は、input
が有効なASCIIでエンコードされたデータのみを含む場合(input
が空の場合を含む)にtrue
を返します。
input
がデタッチされた配列バッファの場合、例外をスローします。
buffer.isUtf8(input)
#
- input <Buffer> | <ArrayBuffer> | <TypedArray> 検証する入力。
- 戻り値: <ブール値>
この関数は、input
が有効なUTF-8でエンコードされたデータのみを含む場合(input
が空の場合を含む)にtrue
を返します。
input
がデタッチされた配列バッファの場合、例外をスローします。
buffer.INSPECT_MAX_BYTES
#
- <integer> **デフォルト:**
50
buf.inspect()
が呼び出されたときに返されるバイト数の最大値を返します。これはユーザーモジュールによってオーバーライドできます。util.inspect()
でbuf.inspect()
の動作の詳細を参照してください。
buffer.kMaxLength
#
- <integer> 単一の
Buffer
インスタンスに対して許可される最大サイズ。
buffer.constants.MAX_LENGTH
のエイリアス。
buffer.kStringMaxLength
#
- <整数> 単一の
string
インスタンスに許容される最大長。
buffer.constants.MAX_STRING_LENGTH
のエイリアスです。
buffer.resolveObjectURL(id)
#
'blob:nodedata:...'
を、URL.createObjectURL()
の以前の呼び出しを使用して登録された関連付けられた <Blob> オブジェクトに解決します。
buffer.transcode(source, fromEnc, toEnc)
#
source
<Buffer> | <Uint8Array>Buffer
またはUint8Array
インスタンス。fromEnc
<文字列> 現在のエンコーディング。toEnc
<文字列> ターゲットエンコーディング。- 戻り値: <Buffer>
指定された 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
では ?
に置き換えられます。
クラス: SlowBuffer
#
Buffer.allocUnsafeSlow()
を代わりに使用してください。Buffer.allocUnsafeSlow()
を参照してください。これは、コンストラクタが常に SlowBuffer
インスタンスではなく Buffer
インスタンスを返すという意味では、クラスではありませんでした。
new SlowBuffer(size)
#
Buffer.allocUnsafeSlow()
を代わりに使用してください。size
<整数> 新しいSlowBuffer
の必要な長さ。
Buffer.allocUnsafeSlow()
を参照してください。
Buffer 定数#
buffer.constants.MAX_LENGTH
#
- <integer> 単一の
Buffer
インスタンスに対して許可される最大サイズ。
32ビットアーキテクチャでは、この値は現在230 - 1(約1 GiB)です。
64ビットアーキテクチャでは、この値は現在232(約4 GiB)です。
内部的には v8::TypedArray::kMaxLength
を反映しています。
この値は buffer.kMaxLength
として使用することもできます。
buffer.constants.MAX_STRING_LENGTH
#
- <整数> 単一の
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
インスタンスは、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(array)
によって返される Buffer
インスタンスは、size
が Buffer.poolSize
の半分以下である場合、共有内部メモリプールから割り当てられる可能性があります。Buffer.allocUnsafeSlow()
によって返されるインスタンスは、決して共有内部メモリプールを使用しません。
--zero-fill-buffers
コマンドラインオプション#
Node.js は、--zero-fill-buffers
コマンドラインオプションを使用して起動できます。これにより、デフォルトで作成時にすべての新しく割り当てられた Buffer
インスタンスがゼロで埋められるようになります。このオプションがない場合、Buffer.allocUnsafe()
、Buffer.allocUnsafeSlow()
、および new SlowBuffer(size)
で作成されたバッファはゼロで埋められません。このフラグの使用は、パフォーマンスに測定可能な悪影響を与える可能性があります。新しく割り当てられた Buffer
インスタンスが、潜在的に機密性の高い古いデータを含まないことを強制的に適用する必要がある場合にのみ、--zero-fill-buffers
オプションを使用してください。
$ 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()
の使用には明確なパフォーマンス上の利点がありますが、アプリケーションにセキュリティ上の脆弱性を導入しないように、特別な注意を払う必要があります。