コンテンツにスキップ
UniKVS
日本語
Esc
↑↓移動↵開く⌘Jプレビュー
このページの内容

@unikvs/utils

@unikvs/utils の使い方です。ファイル名の検証、バイト列操作、ストリーム変換を提供します。

概要

@unikvs/utils は、ファイル名やディレクトリ名の検証、バイト列の変換や分割、反復可能オブジェクトから ReadableStream への変換などを提供するパッケージです。

プラグイン実装者向け

次のコマンドでインストールできます。

npm install @unikvs/utils
pnpm add @unikvs/utils
yarn add @unikvs/utils
bun add @unikvs/utils
nub add @unikvs/utils
aube add @unikvs/utils
import {
  assertValidFilename,
  assertValidDirname,
  bytesToHex,
  chunks,
  isValidFilename,
  isValidDirname,
  toReadableStream,
  withReadableStreamFrom,
  InvalidDirnameError,
  InvalidFilenameError,
} from "@unikvs/utils";

ファイル名の検証

Windows・macOS・Linux で使えるファイル名か検証します。

isValidFilename

function isValidFilename(filename: string): boolean;

使えない名前の場合は false を返します。例外は投げません。

import { isValidFilename } from "@unikvs/utils";

if (isValidFilename("report.txt")) {
  console.log("利用可能なファイル名です。");
}

assertValidFilename

function assertValidFilename(filename: string): void;

有効なら何もせずに戻り、無効なら InvalidFilenameError を投げます。

import { assertValidFilename } from "@unikvs/utils";

assertValidFilename("report.txt");

ディレクトリ名の検証

Windows・macOS・Linux で使えるディレクトリ名か検証します。

isValidDirname

function isValidDirname(dirname: string): boolean;

有効なら true を、無効なら false を返します。例外は投げません。

import { isValidDirname } from "@unikvs/utils";

if (!isValidDirname("my-dir")) {
  console.log("利用できないディレクトリ名です。");
}

assertValidDirname

function assertValidDirname(dirname: string): void;

有効なら何もせずに戻り、無効なら InvalidDirnameError を投げます。

import { assertValidDirname } from "@unikvs/utils";

assertValidDirname("my-dir");

バイト列操作

バイナリーデータの変換と分割を行います。

bytesToHex

function bytesToHex(bytes: Uint8Array): string;

Uint8Array を小文字の 16 進数文字列に変換します。

import { bytesToHex } from "@unikvs/utils";

const hex = bytesToHex(new Uint8Array([0, 255, 16]));
console.log(hex); // "00ff10"

chunks

function chunks<TData extends DataView | ITypedArray>(
  data: TData,
  maxChunkByteSize: number,
): Generator<TData, void, unknown>;

データを指定バイト数ごとに分割し、順に返すジェネレーターを返します。

import { chunks } from "@unikvs/utils";

const data = new Uint8Array([1, 2, 3, 4, 5]);

for (const chunk of chunks(data, 2)) {
  console.log(chunk);
}

ストリーム変換

反復可能オブジェクトを ReadableStream に変換します。

toReadableStream

function toReadableStream<T>(
  iterable: Iterable<T> | AsyncIterable<T>,
): ReadableStream<T>;

同期・非同期の反復可能オブジェクトから ReadableStream を作ります。

import { toReadableStream } from "@unikvs/utils";

const stream = toReadableStream([1, 2, 3]);

for await (const value of stream) {
  console.log(value);
}

withReadableStreamFrom

function withReadableStreamFrom<T>(
  cb: (ReadableStream: ReadableStreamWithFrom) => T,
): T;

ReadableStream.from を使った処理を、対応していない環境でも同じ書き方で実行できます。

import { withReadableStreamFrom } from "@unikvs/utils";

const stream = withReadableStreamFrom((ReadableStream) =>
  ReadableStream.from([1, 2, 3]),
);

エラー

ファイル名・ディレクトリ名の検証エラーです。使えない名前を指定すると投げられます。

エラー 発生条件
InvalidFilenameError 使えないファイル名を指定しました。
InvalidDirnameError 使えないディレクトリ名を指定しました。
import { InvalidFilenameError } from "@unikvs/utils";

throw new InvalidFilenameError({ filename: "../evil" });

使用例

ファイル名の検証・バイナリーの分割・ストリーム変換を組み合わせる例です。

import {
  assertValidFilename,
  chunks,
  InvalidFilenameError,
  toReadableStream,
} from "@unikvs/utils";

async function saveChunks(filename: string, data: Uint8Array): Promise<void> {
  try {
    assertValidFilename(filename);
  } catch (error) {
    if (error instanceof InvalidFilenameError) {
      console.error(`無効なファイル名です: ${error.meta.filename}`);
    }
    throw error;
  }

  const stream = toReadableStream(chunks(data, 64 * 1024));

  for await (const chunk of stream) {
    await writeChunk(filename, chunk);
  }
}

async function writeChunk(filename: string, chunk: Uint8Array): Promise<void> {
  console.log(`${filename}: ${chunk.byteLength} バイトを書き込みます。`);
}

このページは役に立ちましたか?