{"id":13463689,"url":"https://github.com/flatiron/director","last_synced_at":"2025-05-13T16:11:09.133Z","repository":{"id":43918080,"uuid":"626219","full_name":"flatiron/director","owner":"flatiron","description":"a tiny and isomorphic URL router for JavaScript","archived":false,"fork":false,"pushed_at":"2020-12-26T19:39:17.000Z","size":1086,"stargazers_count":5603,"open_issues_count":127,"forks_count":486,"subscribers_count":164,"default_branch":"master","last_synced_at":"2024-10-29T11:30:02.847Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://github.com/flatiron/director","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/flatiron.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2010-04-24T00:22:38.000Z","updated_at":"2024-10-25T09:27:05.000Z","dependencies_parsed_at":"2022-08-30T16:11:41.062Z","dependency_job_id":null,"html_url":"https://github.com/flatiron/director","commit_stats":null,"previous_names":[],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flatiron%2Fdirector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flatiron%2Fdirector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flatiron%2Fdirector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flatiron%2Fdirector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/flatiron","download_url":"https://codeload.github.com/flatiron/director/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247276159,"owners_count":20912288,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T14:00:26.551Z","updated_at":"2025-04-08T23:16:56.021Z","avatar_url":"https://github.com/flatiron.png","language":"JavaScript","readme":"![Logo](https://github.com/flatiron/director/raw/master/img/director.png)\n\n# Synopsis\n\nDirector is a router. Routing is the process of determining what code to run\nwhen a URL is requested.\n\n# Motivation\n\nA routing library that works in both the browser and node.js environments with\nas few differences as possible. Simplifies the development of Single Page Apps\nand Node.js applications. Dependency free (doesn't require jQuery or Express,\netc).\n\n# Status\n[![Build Status](https://secure.travis-ci.org/flatiron/director.png?branch=master)](http://travis-ci.org/flatiron/director)\n\n# Features\n\n* [Client-Side Routing](#client-side-routing)\n* [Server-Side HTTP Routing](#server-side-http-routing)\n* [Server-Side CLI Routing](#server-side-cli-routing)\n\n# Usage\n\n* [API Documentation](#api-documentation)\n* [Frequently Asked Questions](#faq)\n\n## Building client-side script\n\nRun the provided CLI script.\n\n```bash\n./bin/build\n```\n\n## Client-side Routing\n\nIt simply watches the hash of the URL to determine what to do, for example:\n\n```\nhttp://foo.com/#/bar\n```\n\nClient-side routing (aka hash-routing) allows you to specify some information\nabout the state of the application using the URL. So that when the user visits\na specific URL, the application can be transformed accordingly.\n\n![Hash route](https://github.com/flatiron/director/raw/master/img/hashRoute.png)\n\nHere is a simple example:\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003cmeta charset=\"utf-8\"\u003e\n    \u003ctitle\u003eA Gentle Introduction\u003c/title\u003e\n\n    \u003cscript\n      src=\"https://rawgit.com/flatiron/director/master/build/director.min.js\"\u003e\n    \u003c/script\u003e\n\n    \u003cscript\u003e\n      var author = function () { console.log(\"author\"); };\n      var books = function () { console.log(\"books\"); };\n      var viewBook = function (bookId) {\n        console.log(\"viewBook: bookId is populated: \" + bookId);\n      };\n\n      var routes = {\n        '/author': author,\n        '/books': [books, function() {\n          console.log(\"An inline route handler.\");\n        }],\n        '/books/view/:bookId': viewBook\n      };\n\n      var router = Router(routes);\n\n      router.init();\n    \u003c/script\u003e\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n    \u003cul\u003e\n      \u003cli\u003e\u003ca href=\"#/author\"\u003e#/author\u003c/a\u003e\u003c/li\u003e\n      \u003cli\u003e\u003ca href=\"#/books\"\u003e#/books\u003c/a\u003e\u003c/li\u003e\n      \u003cli\u003e\u003ca href=\"#/books/view/1\"\u003e#/books/view/1\u003c/a\u003e\u003c/li\u003e\n    \u003c/ul\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\nDirector works great with your favorite DOM library, such as jQuery.\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003cmeta charset=\"utf-8\"\u003e\n    \u003ctitle\u003eA Gentle Introduction 2\u003c/title\u003e\n\n    \u003cscript\n      src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"\u003e\n    \u003c/script\u003e\n\n    \u003cscript\n      src=\"https://rawgit.com/flatiron/director/master/build/director.min.js\"\u003e\n    \u003c/script\u003e\n\n    \u003cscript\u003e\n    $('document').ready(function() {\n      //\n      // create some functions to be executed when\n      // the correct route is issued by the user.\n      //\n      var showAuthorInfo = function () { console.log(\"showAuthorInfo\"); };\n      var listBooks = function () { console.log(\"listBooks\"); };\n\n      var allroutes = function() {\n        var route = window.location.hash.slice(2);\n        var sections = $('section');\n        var section;\n\n        section = sections.filter('[data-route=' + route + ']');\n\n        if (section.length) {\n          sections.hide(250);\n          section.show(250);\n        }\n      };\n\n      //\n      // define the routing table.\n      //\n      var routes = {\n        '/author': showAuthorInfo,\n        '/books': listBooks\n      };\n\n      //\n      // instantiate the router.\n      //\n      var router = Router(routes);\n\n      //\n      // a global configuration setting.\n      //\n      router.configure({\n        on: allroutes\n      });\n\n      router.init();\n    });\n    \u003c/script\u003e\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n    \u003csection data-route=\"author\"\u003eAuthor Name\u003c/section\u003e\n    \u003csection data-route=\"books\"\u003eBook1, Book2, Book3\u003c/section\u003e\n    \u003cul\u003e\n      \u003cli\u003e\u003ca href=\"#/author\"\u003e#/author\u003c/a\u003e\u003c/li\u003e\n      \u003cli\u003e\u003ca href=\"#/books\"\u003e#/books\u003c/a\u003e\u003c/li\u003e\n    \u003c/ul\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\nYou can find a browser-specific build of `director` [here][1] which has all of\nthe server code stripped away.\n\n## Server-Side HTTP Routing\n\nDirector handles routing for HTTP requests similar to `journey` or `express`:\n\n```js\n  //\n  // require the native http module, as well as director.\n  //\n  var http = require('http'),\n      director = require('director');\n\n  //\n  // create some logic to be routed to.\n  //\n  function helloWorld() {\n    this.res.writeHead(200, { 'Content-Type': 'text/plain' })\n    this.res.end('hello world');\n  }\n\n  //\n  // define a routing table.\n  //\n  var router = new director.http.Router({\n    '/hello': {\n      get: helloWorld\n    }\n  });\n\n  //\n  // setup a server and when there is a request, dispatch the\n  // route that was requested in the request object.\n  //\n  var server = http.createServer(function (req, res) {\n    router.dispatch(req, res, function (err) {\n      if (err) {\n        res.writeHead(404);\n        res.end();\n      }\n    });\n  });\n\n  //\n  // You can also do ad-hoc routing, similar to `journey` or `express`.\n  // This can be done with a string or a regexp.\n  //\n  router.get('/bonjour', helloWorld);\n  router.get(/hola/, helloWorld);\n\n  //\n  // set the server to listen on port `8080`.\n  //\n  server.listen(8080);\n```\n\n### See Also:\n\n - Auto-generated Node.js API Clients for routers using\n   [Director-Reflector](http://github.com/flatiron/director-reflector)\n - RESTful Resource routing using [restful](http://github.com/flatiron/restful)\n - HTML / Plain Text views of routers using\n   [Director-Explorer](http://github.com/flatiron/director-explorer)\n\n## Server-Side CLI Routing\n\nDirector supports Command Line Interface routing. Routes for cli options are\nbased on command line input (i.e. `process.argv`) instead of a URL.\n\n``` js\n  var director = require('director');\n\n  var router = new director.cli.Router();\n\n  router.on('create', function () {\n    console.log('create something');\n  });\n\n  router.on(/destroy/, function () {\n    console.log('destroy something');\n  });\n\n  // You will need to dispatch the cli arguments yourself\n  router.dispatch('on', process.argv.slice(2).join(' '));\n```\n\nUsing the cli router, you can dispatch commands by passing them as a string.\nFor example, if this example is in a file called `foo.js`:\n\n```bash\n$ node foo.js create\ncreate something\n$ node foo.js destroy\ndestroy something\n```\n\n# API Documentation\n\n* [Constructor](#constructor)\n* [Routing Table](#routing-table)\n* [Adhoc Routing](#adhoc-routing)\n* [Scoped Routing](#scoped-routing)\n* [Routing Events](#routing-events)\n* [Configuration](#configuration)\n* [URL Matching](#url-matching)\n* [URL Parameters](#url-parameters)\n* [Wildcard routes](#wildcard-routes)\n* [Route Recursion](#route-recursion)\n* [Async Routing](#async-routing)\n* [Resources](#resources)\n* [History API](#history-api)\n* [Instance Methods](#instance-methods)\n* [Attach Properties to `this`](#attach-properties-to-this)\n* [HTTP Streaming and Body Parsing](#http-streaming-and-body-parsing)\n\n## Constructor\n\n``` js\n  var router = Router(routes);\n```\n\n## Routing Table\n\nAn object literal that contains nested route definitions. A potentially nested\nset of key/value pairs. The keys in the object literal represent each potential\npart of the URL. The values in the object literal contain references to the\nfunctions that should be associated with them. *bark* and *meow* are two\nfunctions that you have defined in your code.\n\n``` js\n  //\n  // Assign routes to an object literal.\n  //\n  var routes = {\n    //\n    // a route which assigns the function `bark`.\n    //\n    '/dog': bark,\n    //\n    // a route which assigns the functions `meow` and `scratch`.\n    //\n    '/cat': [meow, scratch]\n  };\n\n  //\n  // Instantiate the router.\n  //\n  var router = Router(routes);\n```\n\n## Adhoc Routing\n\nWhen developing large client-side or server-side applications it is not always\npossible to define routes in one location. Usually individual decoupled\ncomponents register their own routes with the application router. We refer to\nthis as _Adhoc Routing._ Lets take a look at the API `director` exposes for\nadhoc routing:\n\n**Client-side Routing**\n\n``` js\n  var router = new Router().init();\n\n  router.on('/some/resource', function () {\n    //\n    // Do something on `/#/some/resource`\n    //\n  });\n```\n\n**HTTP Routing**\n\n``` js\n  var router = new director.http.Router();\n\n  router.get(/\\/some\\/resource/, function () {\n    //\n    // Do something on an GET to `/some/resource`\n    //\n  });\n```\n\n## Scoped Routing\n\nIn large web appliations, both [Client-side](#client-side) and\n[Server-side](#http-routing), routes are often scoped within a few individual\nresources. Director exposes a simple way to do this for [Adhoc\nRouting](#adhoc-routing) scenarios:\n\n``` js\n  var router = new director.http.Router();\n\n  //\n  // Create routes inside the `/users` scope.\n  //\n  router.path(/\\/users\\/(\\w+)/, function () {\n    //\n    // The `this` context of the function passed to `.path()`\n    // is the Router itself.\n    //\n\n    this.post(function (id) {\n      //\n      // Create the user with the specified `id`.\n      //\n    });\n\n    this.get(function (id) {\n      //\n      // Retreive the user with the specified `id`.\n      //\n    });\n\n    this.get(/\\/friends/, function (id) {\n      //\n      // Get the friends for the user with the specified `id`.\n      //\n    });\n  });\n```\n\n## Routing Events\n\nIn `director`, a \"routing event\" is a named property in the\n[Routing Table](#routing-table) which can be assigned to a function or an Array\nof functions to be called when a route is matched in a call to\n`router.dispatch()`.\n\n* **on:** A function or Array of functions to execute when the route is matched.\n* **before:** A function or Array of functions to execute before calling the\n  `on` method(s).\n\n**Client-side only**\n\n* **after:** A function or Array of functions to execute when leaving a\n  particular route.\n* **once:** A function or Array of functions to execute only once for a\n  particular route.\n\n## Configuration\n\nGiven the flexible nature of `director` there are several options available for\nboth the [Client-side](#client-side) and [Server-side](#http-routing). These\noptions can be set using the `.configure()` method:\n\n``` js\n  var router = new director.Router(routes).configure(options);\n```\n\nThe `options` are:\n\n* **recurse:** Controls [route recursion](#route-recursion). Use `forward`,\n  `backward`, or `false`. Default is `false` Client-side, and `backward`\n  Server-side.\n* **strict:** If set to `false`, then trailing slashes (or other delimiters)\n  are allowed in routes. Default is `true`.\n* **async:** Controls [async routing](#async-routing). Use `true` or `false`.\n  Default is `false`.\n* **delimiter:** Character separator between route fragments. Default is `/`.\n* **notfound:** A function to call if no route is found on a call to\n  `router.dispatch()`.\n* **on:** A function (or list of functions) to call on every call to\n  `router.dispatch()` when a route is found.\n* **before:** A function (or list of functions) to call before every call to\n  `router.dispatch()` when a route is found.\n\n**Client-side only**\n\n* **resource:** An object to which string-based routes will be bound. This can\n  be especially useful for late-binding to route functions (such as async\n  client-side requires).\n* **after:** A function (or list of functions) to call when a given route is no\n  longer the active route.\n* **html5history:** If set to `true` and client supports `pushState()`, then\n  uses HTML5 History API instead of hash fragments. See\n  [History API](#history-api) for more information.\n* **run_handler_in_init:** If `html5history` is enabled, the route handler by\n  default is executed upon `Router.init()` since with real URIs the router can\n  not know if it should call a route handler or not. Setting this to `false`\n  disables the route handler initial execution.\n* **convert_hash_in_init:** If `html5history` is enabled, the window.location hash by default is converted to a route upon `Router.init()` since with canonical URIs the router can not know if it should convert the hash to a route or not. Setting this to `false` disables the hash conversion on router initialisation.\n\n## URL Matching\n\n``` js\n  var router = Router({\n    //\n    // given the route '/dog/yella'.\n    //\n    '/dog': {\n      '/:color': {\n        //\n        // this function will return the value 'yella'.\n        //\n        on: function (color) { console.log(color) }\n      }\n    }\n  });\n```\n\nRoutes can sometimes become very complex, `simple/:tokens` don't always\nsuffice. Director supports regular expressions inside the route names. The\nvalues captured from the regular expressions are passed to your listener\nfunction.\n\n``` js\n  var router = Router({\n    //\n    // given the route '/hello/world'.\n    //\n    '/hello': {\n      '/(\\\\w+)': {\n        //\n        // this function will return the value 'world'.\n        //\n        on: function (who) { console.log(who) }\n      }\n    }\n  });\n```\n\n``` js\n  var router = Router({\n    //\n    // given the route '/hello/world/johny/appleseed'.\n    //\n    '/hello': {\n      '/world/?([^\\/]*)\\/([^\\/]*)/?': function (a, b) {\n        console.log(a, b);\n      }\n    }\n  });\n```\n\n## URL Parameters\n\nWhen you are using the same route fragments it is more descriptive to define\nthese fragments by name and then use them in your\n[Routing Table](#routing-table) or [Adhoc Routes](#adhoc-routing). Consider a\nsimple example where a `userId` is used repeatedly.\n\n``` js\n  //\n  // Create a router. This could also be director.cli.Router() or\n  // director.http.Router().\n  //\n  var router = new director.Router();\n\n  //\n  // A route could be defined using the `userId` explicitly.\n  //\n  router.on(/([\\w-_]+)/, function (userId) { });\n\n  //\n  // Define a shorthand for this fragment called `userId`.\n  //\n  router.param('userId', /([\\\\w\\\\-]+)/);\n\n  //\n  // Now multiple routes can be defined with the same\n  // regular expression.\n  //\n  router.on('/anything/:userId', function (userId) { });\n  router.on('/something-else/:userId', function (userId) { });\n```\n\n## Wildcard routes\n\nIt is possible to define wildcard routes, so that /foo and /foo/a/b/c routes to\nthe same handler, and gets passed `\"\"` and `\"a/b/c\"` respectively.\n\n``` js\n  router.on(\"/foo/?((\\w|.)*)\"), function (path) { });\n```\n\n## Route Recursion\n\nCan be assigned the value of `forward` or `backward`. The recurse option will\ndetermine the order in which to fire the listeners that are associated with\nyour routes. If this option is NOT specified or set to null, then only the\nlisteners associated with an exact match will be fired.\n\n### No recursion, with the URL /dog/angry\n\n``` js\n  var routes = {\n    '/dog': {\n      '/angry': {\n        //\n        // Only this method will be fired.\n        //\n        on: growl\n      },\n      on: bark\n    }\n  };\n\n  var router = Router(routes);\n```\n\n### Recursion set to `backward`, with the URL /dog/angry\n\n``` js\n  var routes = {\n    '/dog': {\n      '/angry': {\n        //\n        // This method will be fired first.\n        //\n        on: growl\n      },\n      //\n      // This method will be fired second.\n      //\n      on: bark\n    }\n  };\n\n  var router = Router(routes).configure({ recurse: 'backward' });\n```\n\n### Recursion set to `forward`, with the URL /dog/angry\n\n``` js\n  var routes = {\n    '/dog': {\n      '/angry': {\n        //\n        // This method will be fired second.\n        //\n        on: growl\n      },\n      //\n      // This method will be fired first.\n      //\n      on: bark\n    }\n  };\n\n  var router = Router(routes).configure({ recurse: 'forward' });\n```\n\n### Breaking out of recursion, with the URL /dog/angry\n\n``` js\n  var routes = {\n    '/dog': {\n      '/angry': {\n        //\n        // This method will be fired first.\n        //\n        on: function() { return false; }\n      },\n      //\n      // This method will not be fired.\n      //\n      on: bark\n    }\n  };\n\n  //\n  // This feature works in reverse with recursion set to true.\n  //\n  var router = Router(routes).configure({ recurse: 'backward' });\n```\n\n## Async Routing\n\nBefore diving into how Director exposes async routing, you should understand\n[Route Recursion](#route-recursion). At it's core route recursion is about\nevaluating a series of functions gathered when traversing the [Routing\nTable](#routing-table).\n\nNormally this series of functions is evaluated synchronously. In async routing,\nthese functions are evaluated asynchronously. Async routing can be extremely\nuseful both on the client-side and the server-side:\n\n* **Client-side:** To ensure an animation or other async operations (such as\n  HTTP requests for authentication) have completed before continuing evaluation\n  of a route.\n* **Server-side:** To ensure arbitrary async operations (such as performing\n  authentication) have completed before continuing the evaluation of a route.\n\nThe method signatures for route functions in synchronous and asynchronous\nevaluation are different: async route functions take an additional `next()`\ncallback.\n\n### Synchronous route functions\n\n``` js\n  var router = new director.Router();\n\n  router.on('/:foo/:bar/:bazz', function (foo, bar, bazz) {\n    //\n    // Do something asynchronous with `foo`, `bar`, and `bazz`.\n    //\n  });\n```\n\n### Asynchronous route functions\n\n``` js\n  var router = new director.http.Router().configure({ async: true });\n\n  router.on('/:foo/:bar/:bazz', function (foo, bar, bazz, next) {\n    //\n    // Go do something async, and determine that routing should stop\n    //\n    next(false);\n  });\n```\n\n## Resources\n\n**Available on the Client-side only.** An object literal containing functions.\nIf a host object is specified, your route definitions can provide string\nliterals that represent the function names inside the host object. A host\nobject can provide the means for better encapsulation and design.\n\n``` js\n\n  var router = Router({\n\n    '/hello': {\n      '/usa': 'americas',\n      '/china': 'asia'\n    }\n\n  }).configure({ resource: container }).init();\n\n  var container = {\n    americas: function() { return true; },\n    china: function() { return true; }\n  };\n\n```\n\n## History API\n\n**Available on the Client-side only.** Director supports using HTML5 History\nAPI instead of hash fragments for navigation. To use the API, pass\n`{html5history: true}` to `configure()`. Use of the API is enabled only if the\nclient supports `pushState()`.\n\nUsing the API gives you cleaner URIs but they come with a cost. Unlike with\nhash fragments your route URIs must exist. When the client enters a page, say\nhttp://foo.com/bar/baz, the web server must respond with something meaningful.\nUsually this means that your web server checks the URI points to something\nthat, in a sense, exists, and then serves the client the JavaScript\napplication.\n\nIf you're after a single-page application you can not use plain old `\u003ca\nhref=\"/bar/baz\"\u003e` tags for navigation anymore. When such link is clicked, web\nbrowsers try to ask for the resource from server which is not of course desired\nfor a single-page application. Instead you need to use e.g. click handlers and\ncall the `setRoute()` method yourself.\n\n## Attach Properties To `this`\n\n**Available in the http router only.** Generally, the `this` object bound to\nroute handlers, will contain the request in `this.req` and the response in\n`this.res`. One may attach additional properties to `this` with the\n`router.attach` method:\n\n```js\n  var director = require('director');\n\n  var router = new director.http.Router().configure(options);\n\n  //\n  // Attach properties to `this`\n  //\n  router.attach(function () {\n    this.data = [1,2,3];\n  });\n\n  //\n  // Access properties attached to `this` in your routes!\n  //\n  router.get('/hello', function () {\n    this.res.writeHead(200, { 'content-type': 'text/plain' });\n\n    //\n    // Response will be `[1,2,3]`!\n    //\n    this.res.end(this.data);\n  });\n```\n\nThis API may be used to attach convenience methods to the `this` context of\nroute handlers.\n\n## HTTP Streaming and Body Parsing\n\nWhen you are performing HTTP routing there are two common scenarios:\n\n* Buffer the request body and parse it according to the `Content-Type` header\n  (usually `application/json` or `application/x-www-form-urlencoded`).\n* Stream the request body by manually calling `.pipe` or listening to the\n  `data` and `end` events.\n\nBy default `director.http.Router()` will attempt to parse either the `.chunks`\nor `.body` properties set on the request parameter passed to\n`router.dispatch(request, response, callback)`. The router instance will also\nwait for the `end` event before firing any routes.\n\n**Default Behavior**\n\n``` js\n  var director = require('director');\n\n  var router = new director.http.Router();\n\n  router.get('/', function () {\n    //\n    // This will not work, because all of the data\n    // events and the end event have already fired.\n    //\n    this.req.on('data', function (chunk) {\n      console.log(chunk)\n    });\n  });\n```\n\nIn [flatiron][2], `director` is used in conjunction with [union][3] which uses\na `BufferedStream` proxy to the raw `http.Request` instance. [union][3] will\nset the `req.chunks` property for you and director will automatically parse the\nbody. If you wish to perform this buffering yourself directly with `director`\nyou can use a simple request handler in your http server:\n\n``` js\n  var http = require('http'),\n      director = require('director');\n\n  var router = new director.http.Router();\n\n  var server = http.createServer(function (req, res) {\n    req.chunks = [];\n    req.on('data', function (chunk) {\n      req.chunks.push(chunk.toString());\n    });\n\n    router.dispatch(req, res, function (err) {\n      if (err) {\n        res.writeHead(404);\n        res.end();\n      }\n\n      console.log('Served ' + req.url);\n    });\n  });\n\n  router.post('/', function () {\n    this.res.writeHead(200, { 'Content-Type': 'application/json' })\n    this.res.end(JSON.stringify(this.req.body));\n  });\n```\n\n**Streaming Support**\n\nIf you wish to get access to the request stream before the `end` event is\nfired, you can pass the `{ stream: true }` options to the route.\n\n``` js\n  var director = require('director');\n\n  var router = new director.http.Router();\n\n  router.get('/', { stream: true }, function () {\n    //\n    // This will work because the route handler is invoked\n    // immediately without waiting for the `end` event.\n    //\n    this.req.on('data', function (chunk) {\n      console.log(chunk);\n    });\n  });\n```\n\n## Instance methods\n\n### configure(options)\n\n* `options` {Object}: Options to configure this instance with.\n\nConfigures the Router instance with the specified `options`. See\n[Configuration](#configuration) for more documentation.\n\n### param(token, matcher)\n\n* token {string}: Named parameter token to set to the specified `matcher`\n* matcher {string|Regexp}: Matcher for the specified `token`.\n\nAdds a route fragment for the given string `token` to the specified regex\n`matcher` to this Router instance. See [URL Parameters](#url-parameters) for more\ndocumentation.\n\n### on(method, path, route)\n\n* `method` {string}: Method to insert within the Routing Table (e.g. `on`,\n  `get`, etc.).\n* `path` {string}: Path within the Routing Table to set the `route` to.\n* `route` {function|Array}: Route handler to invoke for the `method` and `path`.\n\nAdds the `route` handler for the specified `method` and `path` within the\n[Routing Table](#routing-table).\n\n### path(path, routesFn)\n\n* `path` {string|Regexp}: Scope within the Routing Table to invoke the\n  `routesFn` within.\n* `routesFn` {function}: Adhoc Routing function with calls to `this.on()`,\n  `this.get()` etc.\n\nInvokes the `routesFn` within the scope of the specified `path` for this Router\ninstance.\n\n### dispatch(method, path[, callback])\n\n* method {string}: Method to invoke handlers for within the Routing Table\n* path {string}: Path within the Routing Table to match\n* callback {function}: Invoked once all route handlers have been called.\n\nDispatches the route handlers matched within the [Routing Table](#routing-table)\nfor this instance for the specified `method` and `path`.\n\n### mount(routes, path)\n\n* routes {object}: Partial routing table to insert into this instance.\n* path {string|Regexp}: Path within the Routing Table to insert the `routes`\n  into.\n\nInserts the partial [Routing Table](#routing-table), `routes`, into the Routing\nTable for this Router instance at the specified `path`.\n\n## Instance methods (Client-side only)\n\n### init([redirect])\n\n* `redirect` {String}: This value will be used if '/#/' is not found in the\n  URL. (e.g., init('/') will resolve to '/#/', init('foo') will resolve to\n  '/#foo').\n\nInitialize the router, start listening for changes to the URL.\n\n### getRoute([index])\n\n* `index` {Number}: The hash value is divided by forward slashes, each section\n  then has an index, if this is provided, only that section of the route will\n  be returned.\n\nReturns the entire route or just a section of it.\n\n### setRoute(route)\n\n* `route` {String}: Supply a route value, such as `home/stats`.\n\nSet the current route.\n\n### setRoute(start, length)\n\n* `start` {Number} - The position at which to start removing items.\n* `length` {Number} - The number of items to remove from the route.\n\nRemove a segment from the current route.\n\n### setRoute(index, value)\n\n* `index` {Number} - The hash value is divided by forward slashes, each section\n  then has an index.\n* `value` {String} - The new value to assign the the position indicated by the\n  first parameter.\n\nSet a segment of the current route.\n\n# Frequently Asked Questions\n\n## What About SEO?\n\nIs using a Client-side router a problem for SEO? Yes. If advertising is a\nrequirement, you are probably building a \"Web Page\" and not a \"Web\nApplication\". Director on the client is meant for script-heavy Web\nApplications.\n\n##### LICENSE: MIT\n##### Author: [Charlie Robbins](https://github.com/indexzero)\n##### Contributors: [Paolo Fragomeni](https://github.com/hij1nx)\n\n[0]: http://github.com/flatiron/director\n[1]: https://github.com/flatiron/director/blob/master/build/director.min.js\n[2]: http://github.com/flatiron/flatiron\n[3]: http://github.com/flatiron/union\n","funding_links":[],"categories":["JavaScript","Routing","Router","Routing [🔝](#readme)","Web Development","8. 路由和链接(Routing And URLs)","路由","Vue","JavaScript Libs"],"sub_categories":["Runner","Web DB","Angular","运行器","运行器e2e测试","PostCSS","Misc"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflatiron%2Fdirector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflatiron%2Fdirector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflatiron%2Fdirector/lists"}