You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

582 lines
19 KiB

9 years ago
11 years ago
11 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
12 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
11 years ago
12 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
12 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
10 years ago
9 years ago
  1. [![view on npm](http://img.shields.io/npm/v/local-web-server.svg)](https://www.npmjs.org/package/local-web-server)
  2. [![npm module downloads](http://img.shields.io/npm/dt/local-web-server.svg)](https://www.npmjs.org/package/local-web-server)
  3. [![Build Status](https://travis-ci.org/75lb/local-web-server.svg?branch=master)](https://travis-ci.org/75lb/local-web-server)
  4. [![Dependency Status](https://david-dm.org/75lb/local-web-server.svg)](https://david-dm.org/75lb/local-web-server)
  5. [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/feross/standard)
  6. ***This is the documentation for the next version. For the previous release, see the [prev](https://github.com/75lb/local-web-server/tree/prev) branch. To install this prerelease: `$ npm i -g local-web-server@next`***
  7. # local-web-server
  8. A simple web-server for productive front-end development. Typical use cases:
  9. * Front-end Development
  10. * Static or Single Page App development
  11. * Re-route paths to local or remote resources
  12. * Bundle with your front-end project
  13. * Very little configuration, just a few options
  14. * Outputs a dynamic statistics view to the terminal
  15. * Configurable log output, compatible with [Goaccess, Logstalgia and glTail](https://github.com/75lb/local-web-server/blob/master/doc/visualisation.md)
  16. * Back-end service mocking
  17. * Prototype a web service, microservice, REST API etc.
  18. * Mocks are defined with config (static), or code (dynamic).
  19. * CORS-friendly, all origins allowed by default.
  20. * Proxy server
  21. * Map local routes to remote servers. Removes CORS pain when consuming remote services.
  22. * File sharing
  23. **Requires node v4.0.0 or higher**.
  24. ## Synopsis
  25. local-web-server is a simple command-line tool. To use it, from your project directory run `ws`.
  26. <pre><code>$ ws --help
  27. <strong>local-web-server</strong>
  28. A simple web-server for productive front-end development.
  29. <strong>Synopsis</strong>
  30. $ ws [&lt;server options&gt;]
  31. $ ws --config
  32. $ ws --help
  33. <strong>Server</strong>
  34. -p, --port number Web server port.
  35. -d, --directory path Root directory, defaults to the current directory.
  36. -f, --log-format string If a format is supplied an access log is written to stdout. If
  37. not, a dynamic statistics view is displayed. Use a preset ('none',
  38. 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a
  39. custom format (e.g. ':method -> :url').
  40. -r, --rewrite expression ... A list of URL rewrite rules. For each rule, separate the 'from'
  41. and 'to' routes with '->'. Whitespace surrounded the routes is
  42. ignored. E.g. '/from -> /to'.
  43. -s, --spa file Path to a Single Page App, e.g. app.html.
  44. -c, --compress Serve gzip-compressed resources, where applicable.
  45. -b, --forbid path ... A list of forbidden routes.
  46. -n, --no-cache Disable etag-based caching -forces loading from disk each request.
  47. --key file SSL key, required for https.
  48. --cert file SSL cert, required for https.
  49. --verbose Verbose output, useful for debugging.
  50. <strong>Misc</strong>
  51. -h, --help Print these usage instructions.
  52. --config Print the stored config.
  53. Project home: https://github.com/75lb/local-web-server
  54. </code></pre>
  55. ## Examples
  56. For the examples below, we assume we're in a project directory looking like this:
  57. ```sh
  58. .
  59. ├── css
  60. │   └── style.css
  61. ├── index.html
  62. └── package.json
  63. ```
  64. All paths/routes are specified using [express syntax](http://expressjs.com/guide/routing.html#route-paths). To run the example projects linked below, clone the project, move into the example directory specified, run `ws`.
  65. ### Static site
  66. Fire up your static site on the default port:
  67. ```sh
  68. $ ws
  69. serving at http://localhost:8000
  70. ```
  71. [Example](https://github.com/75lb/local-web-server/tree/master/example/simple).
  72. ### Single Page Application
  73. You're building a web app with client-side routing, so mark `index.html` as the SPA.
  74. ```sh
  75. $ ws --spa index.html
  76. ```
  77. By default, typical SPA paths (e.g. `/user/1`, `/login`) would return `404 Not Found` as a file does not exist with that path. By marking `index.html` as the SPA you create this rule:
  78. *If a static file at the requested path exists (e.g. `/css/style.css`) then serve it, if it does not (e.g. `/login`) then serve the specified SPA and handle the route client-side.*
  79. [Example](https://github.com/75lb/local-web-server/tree/master/example/spa).
  80. ### URL rewriting
  81. Your application requested `/css/style.css` but it's stored at `/build/css/style.css`. To avoid a 404 you need a rewrite rule:
  82. ```sh
  83. $ ws --rewrite '/css/style.css -> /build/css/style.css'
  84. ```
  85. Or, more generally (matching any stylesheet under `/css`):
  86. ```sh
  87. $ ws --rewrite '/css/:stylesheet -> /build/css/:stylesheet'
  88. ```
  89. With a deep CSS directory structure it may be easier to mount the entire contents of `/build/css` to the `/css` path:
  90. ```sh
  91. $ ws --rewrite '/css/* -> /build/css/$1'
  92. ```
  93. this rewrites `/css/a` as `/build/css/a`, `/css/a/b/c` as `/build/css/a/b/c` etc.
  94. #### Proxied requests
  95. If the `to` URL contains a remote host, local-web-server will act as a proxy - fetching and responding with the remote resource.
  96. Mount the npm registry locally:
  97. ```sh
  98. $ ws --rewrite '/npm/* -> http://registry.npmjs.org/$1'
  99. ```
  100. Map local requests for repo data to the Github API:
  101. ```sh
  102. $ ws --rewrite '/:user/repos/:name -> https://api.github.com/repos/:user/:name'
  103. ```
  104. [Example](https://github.com/75lb/local-web-server/tree/master/example/rewrite).
  105. ### Mock Responses
  106. Mocks give you full control over the response headers and body returned to the client. They can be used to return anything from a simple html string to a resourceful REST API. Typically, they're used to mock services but can be used for anything.
  107. In the config, define an array called `mocks`. Each mock definition maps a <code>[route](http://expressjs.com/guide/routing.html#route-paths)</code> to a `response`. A simple home page:
  108. ```json
  109. {
  110. "mocks": [
  111. {
  112. "route": "/",
  113. "response": {
  114. "body": "<h1>Welcome to the Mock Responses example</h1>"
  115. }
  116. }
  117. ]
  118. }
  119. ```
  120. Under the hood, the property values from the `response` object are written onto the underlying [koa response object](https://github.com/koajs/koa/blob/master/docs/api/response.md). You can set any valid koa response properies, for example [type](https://github.com/koajs/koa/blob/master/docs/api/response.md#responsetype-1):
  121. ```json
  122. {
  123. "mocks": [
  124. {
  125. "route": "/",
  126. "response": {
  127. "type": "text/plain",
  128. "body": "<h1>Welcome to the Mock Responses example</h1>"
  129. }
  130. }
  131. ]
  132. }
  133. ```
  134. #### Conditional Response
  135. To define a conditional response, set a `request` object on the mock definition. The `request` value acts as a query - the response defined will only be returned if each property of the `request` query matches. For example, return an XML response *only* if the request headers include `accept: application/xml`, else return 404 Not Found.
  136. ```json
  137. {
  138. "mocks": [
  139. {
  140. "route": "/two",
  141. "request": { "accepts": "xml" },
  142. "response": {
  143. "body": "<result id='2' name='whatever' />"
  144. }
  145. }
  146. ]
  147. }
  148. ```
  149. #### Multiple Potential Responses
  150. To specify multiple potential responses, set an array of mock definitions to the `responses` property. The first response with a matching request query will be sent. In this example, the client will get one of two responses depending on the request method:
  151. ```json
  152. {
  153. "mocks": [
  154. {
  155. "route": "/three",
  156. "responses": [
  157. {
  158. "request": { "method": "GET" },
  159. "response": {
  160. "body": "<h1>Mock response for 'GET' request on /three</h1>"
  161. }
  162. },
  163. {
  164. "request": { "method": "POST" },
  165. "response": {
  166. "status": 400,
  167. "body": { "message": "That method is not allowed." }
  168. }
  169. }
  170. ]
  171. }
  172. ]
  173. }
  174. ```
  175. #### Dynamic Response
  176. The examples above all returned static data. To define a dynamic response, create a mock module. Specify its path in the `module` property:
  177. ```json
  178. {
  179. "mocks": [
  180. {
  181. "route": "/four",
  182. "module": "/mocks/stream-self.js"
  183. }
  184. ]
  185. }
  186. ```
  187. Here's what the `stream-self` module looks like. The module should export a mock definition (an object, or array of objects, each with a `response` and optional `request`). In this example, the module simply streams itself to the response but you could set `body` to *any* [valid value](https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1).
  188. ```js
  189. const fs = require('fs')
  190. module.exports = {
  191. response: {
  192. body: fs.createReadStream(__filename)
  193. }
  194. }
  195. ```
  196. #### Response function
  197. For more power, define the response as a function. It will receive the [koa context](https://github.com/koajs/koa/blob/master/docs/api/context.md) as its first argument. Now you have full programmatic control over the response returned.
  198. ```js
  199. module.exports = {
  200. response: function (ctx) {
  201. ctx.body = '<h1>I can do anything i want.</h1>'
  202. }
  203. }
  204. ```
  205. If the route contains tokens, their values are passed to the response. For example, with this mock...
  206. ```json
  207. {
  208. "mocks": [
  209. {
  210. "route": "/players/:id",
  211. "module": "/mocks/players.js"
  212. }
  213. ]
  214. }
  215. ```
  216. ...the `id` value is passed to the `response` function. For example, a path of `/players/10?name=Lionel` would pass `10` to the response function. Additional, the value `Lionel` would be available on `ctx.query.name`:
  217. ```js
  218. module.exports = {
  219. response: function (ctx, id) {
  220. ctx.body = `<h1>id: ${id}, name: ${ctx.query.name}</h1>`
  221. }
  222. }
  223. ```
  224. #### RESTful Resource example
  225. Here's an example of a REST collection (users). We'll create two routes, one for actions on the resource collection, one for individual resource actions.
  226. ```json
  227. {
  228. "mocks": [
  229. { "route": "/users", "module": "/mocks/users.js" },
  230. { "route": "/users/:id", "module": "/mocks/user.js" }
  231. ]
  232. }
  233. ```
  234. Define a module (`users.json`) defining seed data:
  235. ```json
  236. [
  237. { "id": 1, "name": "Lloyd", "age": 40, "nationality": "English" },
  238. { "id": 2, "name": "Mona", "age": 34, "nationality": "Palestinian" },
  239. { "id": 3, "name": "Francesco", "age": 24, "nationality": "Italian" }
  240. ]
  241. ```
  242. The collection module:
  243. ```js
  244. const users = require('./users.json')
  245. /* responses for /users */
  246. const mockResponses = [
  247. /* Respond with 400 Bad Request for PUT and DELETE - inappropriate on a collection */
  248. { request: { method: 'PUT' }, response: { status: 400 } },
  249. { request: { method: 'DELETE' }, response: { status: 400 } },
  250. {
  251. /* for GET requests return a subset of data, optionally filtered on 'minAge' and 'nationality' */
  252. request: { method: 'GET' },
  253. response: function (ctx) {
  254. ctx.body = users.filter(user => {
  255. const meetsMinAge = (user.age || 1000) >= (Number(ctx.query.minAge) || 0)
  256. const requiredNationality = user.nationality === (ctx.query.nationality || user.nationality)
  257. return meetsMinAge && requiredNationality
  258. })
  259. }
  260. },
  261. {
  262. /* for POST requests, create a new user and return the path to the new resource */
  263. request: { method: 'POST' },
  264. response: function (ctx) {
  265. const newUser = ctx.request.body
  266. users.push(newUser)
  267. newUser.id = users.length
  268. ctx.status = 201
  269. ctx.response.set('Location', `/users/${newUser.id}`)
  270. }
  271. }
  272. ]
  273. module.exports = mockResponses
  274. ```
  275. The individual resource module:
  276. ```js
  277. const users = require('./users.json')
  278. /* responses for /users/:id */
  279. const mockResponses = [
  280. /* don't support POST here */
  281. { request: { method: 'POST' }, response: { status: 400 } },
  282. /* for GET requests, return a particular user */
  283. {
  284. request: { method: 'GET' },
  285. response: function (ctx, id) {
  286. ctx.body = users.find(user => user.id === Number(id))
  287. }
  288. },
  289. /* for PUT requests, update the record */
  290. {
  291. request: { method: 'PUT' },
  292. response: function (ctx, id) {
  293. const updatedUser = ctx.request.body
  294. const existingUserIndex = users.findIndex(user => user.id === Number(id))
  295. users.splice(existingUserIndex, 1, updatedUser)
  296. ctx.status = 200
  297. }
  298. },
  299. /* DELETE request: remove the record */
  300. {
  301. request: { method: 'DELETE' },
  302. response: function (ctx, id) {
  303. const existingUserIndex = users.findIndex(user => user.id === Number(id))
  304. users.splice(existingUserIndex, 1)
  305. ctx.status = 200
  306. }
  307. }
  308. ]
  309. module.exports = mockResponses
  310. ```
  311. [Example](https://github.com/75lb/local-web-server/tree/master/example/mock).
  312. ### Stored config
  313. Use the same options every time? Persist then to `package.json`:
  314. ```json
  315. {
  316. "name": "example",
  317. "version": "1.0.0",
  318. "local-web-server": {
  319. "port": 8100,
  320. "forbid": "*.json"
  321. }
  322. }
  323. ```
  324. or `.local-web-server.json`
  325. ```json
  326. {
  327. "port": 8100,
  328. "forbid": "*.json"
  329. }
  330. ```
  331. local-web-server will merge and use all config found, searching from the current directory upward. In the case both `package.json` and `.local-web-server.json` config is found in the same directory, `.local-web-server.json` will take precedence. Options set on the command line take precedence over all.
  332. To inspect stored config, run:
  333. ```sh
  334. $ ws --config
  335. ```
  336. ### Logging
  337. By default, local-web-server outputs a simple, dynamic statistics view. To see traditional web server logs, use `--log-format`:
  338. ```sh
  339. $ ws --log-format combined
  340. serving at http://localhost:8000
  341. ::1 - - [16/Nov/2015:11:16:52 +0000] "GET / HTTP/1.1" 200 12290 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2562.0 Safari/537.36"
  342. ```
  343. The format value supplied is passed directly to [morgan](https://github.com/expressjs/morgan). The exception is `--log-format none` which disables all output.
  344. ### Access Control
  345. By default, access to all files is allowed (including dot files). Use `--forbid` to establish a blacklist:
  346. ```sh
  347. $ ws --forbid '*.json' '*.yml'
  348. serving at http://localhost:8000
  349. ```
  350. [Example](https://github.com/75lb/local-web-server/tree/master/example/forbid).
  351. ### Other usage
  352. #### Debugging
  353. Prints information about loaded middleware, arguments, remote proxy fetches etc.
  354. ```sh
  355. $ ws --verbose
  356. ```
  357. #### Compression
  358. Serve gzip-compressed resources, where applicable
  359. ```sh
  360. $ ws --compress
  361. ```
  362. #### Disable caching
  363. Disable etag response headers, forcing resources to be served in full every time.
  364. ```sh
  365. $ ws --no-cache
  366. ```
  367. #### mime-types
  368. You can set additional mime-type/extension mappings, or override the defaults by setting a `mime` value in the stored config. This value is passed directly to [mime.define()](https://github.com/broofa/node-mime#mimedefine). Example:
  369. ```json
  370. {
  371. "mime": {
  372. "text/plain": [ "php", "pl" ]
  373. }
  374. }
  375. ```
  376. [Example](https://github.com/75lb/local-web-server/tree/master/example/mime-override).
  377. #### Log Visualisation
  378. Instructions for how to visualise log output using goaccess, logstalgia or gltail [here](https://github.com/75lb/local-web-server/blob/master/doc/visualisation.md).
  379. ## Install
  380. Ensure [node.js](http://nodejs.org) is installed first. Linux/Mac users may need to run the following commands with `sudo`.
  381. ```sh
  382. $ npm install -g local-web-server
  383. ```
  384. This will install the `ws` tool globally. To see the available options, run:
  385. ```sh
  386. $ ws --help
  387. ```
  388. ## Distribute with your project
  389. The standard convention with client-server applications is to add an `npm start` command to launch the server component.
  390. 1\. Install the server as a dev dependency
  391. ```sh
  392. $ npm install local-web-server --save-dev
  393. ```
  394. 2\. Add a `start` command to your `package.json`:
  395. ```json
  396. {
  397. "name": "example",
  398. "version": "1.0.0",
  399. "local-web-server": {
  400. "port": 8100,
  401. "forbid": "*.json"
  402. },
  403. "scripts": {
  404. "start": "ws"
  405. }
  406. }
  407. ```
  408. 3\. Document how to build and launch your site
  409. ```sh
  410. $ npm install
  411. $ npm start
  412. serving at http://localhost:8100
  413. ```
  414. ## API Reference
  415. * [local-web-server](#module_local-web-server)
  416. * [localWebServer([options])](#exp_module_local-web-server--localWebServer) ⇒ <code>[KoaApplication](https://github.com/koajs/koa/blob/master/docs/api/index.md#application)</code>
  417. * [~rewriteRule](#module_local-web-server--localWebServer..rewriteRule)
  418. <a name="exp_module_local-web-server--localWebServer"></a>
  419. ### localWebServer([options]) ⇒ <code>[KoaApplication](https://github.com/koajs/koa/blob/master/docs/api/index.md#application)</code> ⏏
  420. Returns a Koa application you can launch or mix into an existing app.
  421. **Kind**: Exported function
  422. **Params**
  423. - [options] <code>object</code> - options
  424. - [.static] <code>object</code> - koa-static config
  425. - [.root] <code>string</code> <code> = &quot;.&quot;</code> - root directory
  426. - [.options] <code>string</code> - [options](https://github.com/koajs/static#options)
  427. - [.serveIndex] <code>object</code> - koa-serve-index config
  428. - [.path] <code>string</code> <code> = &quot;.&quot;</code> - root directory
  429. - [.options] <code>string</code> - [options](https://github.com/expressjs/serve-index#options)
  430. - [.forbid] <code>Array.&lt;string&gt;</code> - A list of forbidden routes, each route being an [express route-path](http://expressjs.com/guide/routing.html#route-paths).
  431. - [.spa] <code>string</code> - specify an SPA file to catch requests for everything but static assets.
  432. - [.log] <code>object</code> - [morgan](https://github.com/expressjs/morgan) config
  433. - [.format] <code>string</code> - [log format](https://github.com/expressjs/morgan#predefined-formats)
  434. - [.options] <code>object</code> - [options](https://github.com/expressjs/morgan#options)
  435. - [.compress] <code>boolean</code> - Serve gzip-compressed resources, where applicable
  436. - [.mime] <code>object</code> - A list of mime-type overrides, passed directly to [mime.define()](https://github.com/broofa/node-mime#mimedefine)
  437. - [.rewrite] <code>[Array.&lt;rewriteRule&gt;](#module_local-web-server--localWebServer..rewriteRule)</code> - One or more rewrite rules
  438. - [.verbose] <code>boolean</code> - Print detailed output, useful for debugging
  439. **Example**
  440. ```js
  441. const localWebServer = require('local-web-server')
  442. localWebServer().listen(8000)
  443. ```
  444. <a name="module_local-web-server--localWebServer..rewriteRule"></a>
  445. #### localWebServer~rewriteRule
  446. The `from` and `to` routes are specified using [express route-paths](http://expressjs.com/guide/routing.html#route-paths)
  447. **Kind**: inner typedef of <code>[localWebServer](#exp_module_local-web-server--localWebServer)</code>
  448. **Properties**
  449. | Name | Type | Description |
  450. | --- | --- | --- |
  451. | from | <code>string</code> | request route |
  452. | to | <code>string</code> | target route |
  453. **Example**
  454. ```json
  455. {
  456. "rewrite": [
  457. { "from": "/css/*", "to": "/build/styles/$1" },
  458. { "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
  459. { "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
  460. ]
  461. }
  462. ```
  463. * * *
  464. &copy; 2015 Lloyd Brookes <75pound@gmail.com>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).