V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fundon
V2EX  ›  Node.js

pathing - 一個簡單 URL path 詞法分析器

  •  1
     
  •   fundon · 2014-06-05 22:45:10 +08:00 · 2844 次点击
    这是一个创建于 3895 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://github.com/fundon/pathing

    語法:默認使用{}作爲標籤分隔符。

    /posts/{id}       默認使用 [^/]+ 正則表達式.
    /posts/{id:\\d+}  使用 `\d+` 正則表達式.
    

    用例:

    var pathing = require('pathing');
    var tokens = pathing('/{controller}/{action}/{id:\\d+}');
    /*
    tokens:
      [
        { name: 'SLASH', value: '/', pos: 0 },
        { name: 'PLACEHOLDER', value: 'controller', pos: 1, regexp: '[^/]+' },
        { name: 'SLASH', value: '/', pos: 13 },
        { name: 'PLACEHOLDER', value: 'action', pos: 14, regexp: '[^/]+' }
        { name: 'SLASH', value: '/', pos: 22 },
        { name: 'PLACEHOLDER', value: 'id', pos: 23, regexp: '\\d+' } ]
      ]
    */
    
    var tokens = pathing('{year}-{month}-{day}');
    /*
    tokens:
      [
        { name: 'PLACEHOLDER', value: 'year', pos: 0, regexp: '[^/]+' },
        { name: 'IDENTIFIER', value: '-', pos: 6 },
        { name: 'PLACEHOLDER', value: 'month', pos: 7, regexp: '[^/]+' },
        { name: 'IDENTIFIER', value: '-', pos: 14 },
        { name: 'PLACEHOLDER', value: 'day', pos: 15, regexp: '[^/]+' }
      ]
    */

    自定義分隔符:

    var tokens = pathing('/posts/<id>', { open: '<', close: '>' });
    /*
    tokens:
      [
        { name: 'SLASH', value: '/', pos: 0 },
        { name: 'IDENTIFIER', value: 'posts', pos: 1 },
        { name: 'SLASH', value: '/', pos: 6 },
        { name: 'PLACEHOLDER', value: 'id', pos: 7, regexp: '[^/]+' }
      ]
    */

    性能

    $ make benchmark
    
    path-to-regexp x 123,819 ops/sec ±1.33% (92 runs sampled)
    path-to-regexp#mutil-parameters x 155,711 ops/sec ±1.21% (89 runs sampled)
    path-to-regexp#longest x 76,582 ops/sec ±1.78% (88 runs sampled)
    path-to-regexp#longest... x 44,179 ops/sec ±2.39% (81 runs sampled)
    path-to-regexp#special-characters x 426,990 ops/sec ±1.71% (90 runs sampled)
    pathing x 1,338,739 ops/sec ±1.72% (88 runs sampled)
    pathing#mutil-parameters x 762,336 ops/sec ±1.25% (90 runs sampled)
    pathing#longest x 230,568 ops/sec ±1.54% (90 runs sampled)
    pathing#longest... x 116,395 ops/sec ±1.51% (92 runs sampled)
    pathing#special-characters x 1,730,056 ops/sec ±1.95% (86 runs sampled)
    Fastest is pathing#special-characters.
    
    view raw pathing.md hosted with ❤ by GitHub
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1760 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:10 · PVG 09:10 · LAX 17:10 · JFK 20:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.