Webエンジニア向けプログラミング解説動画をYouTubeで配信中!
▶ チャンネル登録はこちら

【Node.js24.x】Object::readv()メソッドの使い方

readvメソッドの使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

readvメソッドは、Node.jsにおいて、オブジェクトのコンテキストで利用される可能性のある機能として、データソースから複数のバッファへ効率的にデータを読み込むことを可能にするメソッドです。このメソッドの主な目的は、一度の操作で複数の独立したメモリ領域(バッファ)にデータを分散して格納することです。

具体的には、ファイルディスクリプタやネットワークソケットなどの入力元からデータを取得し、それを事前に指定されたバッファの配列に、それぞれのバッファが持つ容量に応じて順次書き込んでいきます。これにより、データ読み込みのために複数回システムコールを発行する必要がなくなり、オペレーティングシステムとのやり取りのオーバーヘッドを削減し、I/O処理全体のパフォーマンスを向上させることができます。

特に、アプリケーションが異なる種類のデータや、大きなデータの断片を別々のメモリ領域に直接格納したい場合に非常に有効です。例えば、ファイルからヘッダ、ボディ、フッタをそれぞれ異なるバッファに効率良く読み込む際などに活用できます。メソッドの実行が完了すると、実際に読み込まれた合計バイト数が返され、それによってどれだけのデータが転送されたかを確認できます。この機能は、高速なデータ処理が求められるシステム開発において重要な役割を果たします。

構文(syntax)

1import { open, readv } from 'node:fs/promises';
2import { Buffer } from 'node:buffer';
3import { writeFile, unlink } from 'node:fs/promises';
4
5async function demonstrateReadvSyntax() {
6  const filePath = 'temp-readv-file.txt';
7  await writeFile(filePath, 'Hello world for readv!'); // Create a temporary file
8
9  let filehandle;
10  try {
11    filehandle = await open(filePath, 'r');
12    const fd = filehandle.fd; // Obtain a file descriptor
13
14    const bufferA = Buffer.alloc(5);  // First buffer to read into
15    const bufferB = Buffer.alloc(6);  // Second buffer to read into
16    const allBuffers = [bufferA, bufferB]; // Array of buffers
17
18    // The core syntax for calling the `readv` method:
19    const { bytesRead, buffers: filledBuffers } = await readv(fd, allBuffers, 0);
20
21    // `fd`: The file descriptor to read from.
22    // `allBuffers`: An array of `Buffer` or `Uint8Array` instances to scatter the data into.
23    // `0`: The offset in the file from which to begin reading (optional, defaults to current file position if omitted or null).
24    // The method returns an object containing the total `bytesRead` and the `buffers` array with data.
25
26  } finally {
27    if (filehandle) {
28      await filehandle.close(); // Close the file handle
29    }
30    await unlink(filePath); // Clean up the temporary file
31  }
32}
33
34demonstrateReadvSyntax();

引数(parameters)

fd, buffers, position, callback

  • fd: number: 読み込むファイルディスクリプタ。
  • buffers: Array<Uint8Array | ArrayBuffer | DataView>: 読み込んだデータを格納するバッファの配列。
  • position: number: ファイルのどこから読み込みを開始するかを指定するオフセット。
  • callback: Function: 読み込み操作が完了した後に実行されるコールバック関数。

戻り値(return)

戻り値なし

戻り値はありません

関連コンテンツ

関連プログラミング言語