path-to-regexp vs path-browserify vs path vs upath2 vs upath
Node.jsとブラウザのパス操作ライブラリ
path-to-regexppath-browserifypathupath2upath類似パッケージ:

Node.jsとブラウザのパス操作ライブラリ

これらのライブラリは、ファイルシステムのパスやURLの操作を簡素化するために使用されます。特に、Node.js環境やブラウザ環境でのパスの解析、結合、正規化を行うための便利な機能を提供します。これにより、開発者は異なる環境間でのパスの取り扱いを一貫して行うことができます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
path-to-regexp159,231,9218,57456.3 kB86ヶ月前MIT
path-browserify29,395,299191-156年前MIT
path4,659,773135-1410年前MIT
upath298,807254 kB19日前ISC
upath0154-35年前MIT

機能比較: path-to-regexp vs path-browserify vs path vs upath2 vs upath

パスの結合

  • path-to-regexp:

    'path-to-regexp'は、パスの結合機能は提供していませんが、URLパターンを正規表現に変換するための機能を提供します。

  • path-browserify:

    'path-browserify'も同様に、'join'メソッドを提供し、ブラウザ環境でのパス結合を可能にします。

  • path:

    'path'は、複数のパスを結合するための'join'メソッドを提供します。このメソッドは、OSに依存したパス区切り文字を自動的に使用して、正しいパスを生成します。

  • upath2:

    'upath2'も同様に、'join'メソッドを提供し、より多くの機能を追加しています。

  • upath:

    'upath'は、異なるプラットフォーム間でのパスの結合を行うための'join'メソッドを提供し、WindowsとUnix系のパスを適切に処理します。

パスの正規化

  • path-to-regexp:

    'path-to-regexp'は、正規化機能は提供していませんが、URLのパターンマッチングに特化しています。

  • path-browserify:

    'path-browserify'も'normalize'メソッドを提供し、ブラウザ環境でも同様の正規化が可能です。

  • path:

    'path'は、'normalize'メソッドを使用して、与えられたパスを正規化し、冗長な要素を取り除くことができます。

  • upath2:

    'upath2'も同様に、正規化機能を提供し、より多くのユースケースに対応しています。

  • upath:

    'upath'は、'normalize'メソッドを使用して、異なるプラットフォーム間でのパスの正規化を行います。

プラットフォーム互換性

  • path-to-regexp:

    'path-to-regexp'は、プラットフォームに依存しないため、どの環境でも使用可能です。

  • path-browserify:

    'path-browserify'は、ブラウザ環境でNode.jsの'path'の機能を模倣し、クライアントサイドでのパス操作を可能にします。

  • path:

    'path'はNode.js専用であり、主にサーバーサイドのファイルシステム操作に使用されます。

  • upath2:

    'upath2'も同様に、プラットフォーム互換性を重視して設計されています。

  • upath:

    'upath'は、WindowsとUnix系のパスを一貫して扱うため、クロスプラットフォームの開発に適しています。

使用シナリオ

  • path-to-regexp:

    URLルーティングやパターンマッチングが必要な場合に使用されます。

  • path-browserify:

    ブラウザでNode.jsスタイルのパス操作を行いたい場合に使用されます。

  • path:

    ファイルシステムのパス操作が必要なNode.jsアプリケーションで使用されます。

  • upath2:

    'upath'の機能を拡張したい場合に使用されます。

  • upath:

    異なるプラットフォーム間でのパスの互換性が必要な場合に使用されます。

メンテナンスとサポート

  • path-to-regexp:

    軽量でシンプルなライブラリであり、特定の目的に特化しているため、メンテナンスが容易です。

  • path-browserify:

    コミュニティによってメンテナンスされており、ブラウザ環境での使用に適しています。

  • path:

    Node.jsの公式モジュールであり、広く使用されているため、信頼性が高いです。

  • upath2:

    'upath'の改良版であり、継続的に更新されています。

  • upath:

    活発にメンテナンスされており、クロスプラットフォームのニーズに応じた機能が追加されています。

選び方: path-to-regexp vs path-browserify vs path vs upath2 vs upath

  • path-to-regexp:

    URLパターンを正規表現に変換したい場合は、'path-to-regexp'を選択してください。これは、ルーティングやURLマッチングに特化したライブラリです。

  • path-browserify:

    ブラウザ環境でNode.jsの'path'モジュールの機能を模倣したい場合は、'path-browserify'を選択してください。これにより、ブラウザでもNode.jsスタイルのパス操作が可能になります。

  • path:

    Node.js環境でのファイルシステム操作が必要な場合は、'path'を選択してください。これはNode.jsの組み込みモジュールであり、ファイルパスの操作に特化しています。

  • upath2:

    'upath'の改良版を求める場合は、'upath2'を選択してください。これは、'upath'の機能を拡張し、より多くのユースケースに対応しています。

  • upath:

    異なるプラットフォーム間でのパスの互換性を重視する場合は、'upath'を選択してください。これは、WindowsとUnix系のパスを一貫して扱うことができるライブラリです。

path-to-regexp のREADME

Path-to-RegExp

Turn a path string such as /user/:name into a regular expression.

NPM version NPM downloads Build status Build coverage License

Installation

npm install path-to-regexp --save

Usage

const {
  match,
  pathToRegexp,
  compile,
  parse,
  stringify,
} = require("path-to-regexp");

Parameters

Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name").

const fn = match("/:foo/:bar");

fn("/test/route");
//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }

Wildcard

Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo).

const fn = match("/*splat");

fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }

Optional

Braces can be used to define parts of the path that are optional.

const fn = match("/users{/:id}/delete");

fn("/users/delete");
//=> { path: '/users/delete', params: {} }

fn("/users/123/delete");
//=> { path: '/users/123/delete', params: { id: '123' } }

Match

The match function returns a function for matching strings against a path:

  • path String, TokenData object, or array of strings and TokenData objects.
  • options (optional) (Extends pathToRegexp options)
    • decode Function for decoding strings to params, or false to disable all processing. (default: decodeURIComponent)
const fn = match("/foo/:bar");

Please note: path-to-regexp is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).

PathToRegexp

The pathToRegexp function returns the regexp for matching strings against paths, and an array of keys for understanding the RegExp#exec matches.

  • path String, TokenData object, or array of strings and TokenData objects.
  • options (optional) (See parse for more options)
    • sensitive Regexp will be case sensitive. (default: false)
    • end Validate the match reaches the end of the string. (default: true)
    • delimiter The default delimiter for segments, e.g. [^/] for :named parameters. (default: '/')
    • trailing Allows optional trailing delimiter to match. (default: true)
const { regexp, keys } = pathToRegexp("/foo/:bar");

regexp.exec("/foo/123"); //=> ["/foo/123", "123"]

Compile ("Reverse" Path-To-RegExp)

The compile function will return a function for transforming parameters into a valid path:

  • path A string or TokenData object.
  • options (See parse for more options)
    • delimiter The default delimiter for segments, e.g. [^/] for :named parameters. (default: '/')
    • encode Function for encoding input strings for output into the path, or false to disable entirely. (default: encodeURIComponent)
const toPath = compile("/user/:id");

toPath({ id: "name" }); //=> "/user/name"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"

const toPathRepeated = compile("/*segment");

toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"

// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
const toPathRaw = compile("/user/:id", { encode: false });

toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"

Stringify

Transform a TokenData object to a Path-to-RegExp string.

  • data A TokenData object.
const data = {
  tokens: [
    { type: "text", value: "/" },
    { type: "param", name: "foo" },
  ],
};

const path = stringify(data); //=> "/:foo"

Developers

  • If you are rewriting paths with match and compile, consider using encode: false and decode: false to keep raw paths passed around.
  • To ensure matches work on paths containing characters usually encoded, such as emoji, consider using encodeurl for encodePath.

Parse

The parse function accepts a string and returns TokenData, which can be used with match and compile.

  • path A string.
  • options (optional)
    • encodePath A function for encoding input strings. (default: x => x, recommended: encodeurl)

Tokens

TokenData has two properties:

  • tokens A sequence of tokens, currently of types text, parameter, wildcard, or group.
  • originalPath The original path used with parse, shown in error messages to assist debugging.

Custom path

In some applications you may not be able to use the path-to-regexp syntax, but you still want to use this library for match and compile. For example:

import { match } from "path-to-regexp";

const tokens = [
  { type: "text", value: "/" },
  { type: "parameter", name: "foo" },
];
const originalPath = "/[foo]"; // To help debug error messages.
const path = { tokens, originalPath };
const fn = match(path);

fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } }

Errors

An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.

Missing parameter name

Parameter names must be provided after : or *, for example /*path. They can be valid JavaScript identifiers (e.g. :myName) or JSON strings (:"my-name").

Unexpected ? or +

In past releases, ?, *, and + were used to denote optional or repeating parameters. As an alternative, try these:

  • For optional (?), use braces: /file{.:ext}.
  • For one or more (+), use a wildcard: /*path.
  • For zero or more (*), use both: /files{/*path}.

Unexpected (, ), [, ], etc.

Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To match these characters literally, escape them with a backslash, e.g. "\\(".

Unterminated quote

Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, :"foo.

Express <= 4.x

Path-To-RegExp breaks compatibility with Express <= 4.x in the following ways:

  • The wildcard * must have a name and matches the behavior of parameters :.
  • The optional character ? is no longer supported, use braces instead: /:file{.:ext}.
  • Regexp characters are not supported.
  • Some characters have been reserved to avoid confusion during upgrade (()[]?+!).
  • Parameter names now support valid JavaScript identifiers, or quoted like :"this".

License

MIT