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.

489 lines
16 KiB

9 years ago
11 years ago
11 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
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` 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. --verbose Verbose output, useful for debugging.
  48. <strong>Misc</strong>
  49. -h, --help Print these usage instructions.
  50. --config Print the stored config.
  51. Project home: https://github.com/75lb/local-web-server
  52. </code></pre>
  53. ## Examples
  54. For the examples below, we assume we're in a project directory looking like this:
  55. ```sh
  56. .
  57. ├── css
  58. │   └── style.css
  59. ├── index.html
  60. └── package.json
  61. ```
  62. 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`.
  63. ### Static site
  64. Fire up your static site on the default port:
  65. ```sh
  66. $ ws
  67. serving at http://localhost:8000
  68. ```
  69. [Example](https://github.com/75lb/local-web-server/tree/master/example/simple).
  70. ### Single Page Application
  71. You're building a web app with client-side routing, so mark `index.html` as the SPA.
  72. ```sh
  73. $ ws --spa index.html
  74. ```
  75. 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:
  76. *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.*
  77. [Example](https://github.com/75lb/local-web-server/tree/master/example/spa).
  78. ### URL rewriting
  79. Your application requested `/css/style.css` but it's stored at `/build/css/style.css`. To avoid a 404 you need a rewrite rule:
  80. ```sh
  81. $ ws --rewrite '/css/style.css -> /build/css/style.css'
  82. ```
  83. Or, more generally (matching any stylesheet under `/css`):
  84. ```sh
  85. $ ws --rewrite '/css/:stylesheet -> /build/css/:stylesheet'
  86. ```
  87. With a deep CSS directory structure it may be easier to mount the entire contents of `/build/css` to the `/css` path:
  88. ```sh
  89. $ ws --rewrite '/css/* -> /build/css/$1'
  90. ```
  91. this rewrites `/css/a` as `/build/css/a`, `/css/a/b/c` as `/build/css/a/b/c` etc.
  92. #### Proxied requests
  93. If the `to` URL contains a remote host, local-web-server will act as a proxy - fetching and responding with the remote resource.
  94. Mount the npm registry locally:
  95. ```sh
  96. $ ws --rewrite '/npm/* -> http://registry.npmjs.org/$1'
  97. ```
  98. Map local requests for repo data to the Github API:
  99. ```sh
  100. $ ws --rewrite '/:user/repos/:name -> https://api.github.com/repos/:user/:name'
  101. ```
  102. [Example](https://github.com/75lb/local-web-server/tree/master/example/rewrite).
  103. ### Mock Responses
  104. 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.
  105. 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:
  106. ```json
  107. {
  108. "mocks": [
  109. {
  110. "route": "/",
  111. "response": {
  112. "body": "<h1>Welcome to the Mock Responses example</h1>"
  113. }
  114. }
  115. ]
  116. }
  117. ```
  118. 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):
  119. ```json
  120. {
  121. "mocks": [
  122. {
  123. "route": "/",
  124. "response": {
  125. "type": "text/plain",
  126. "body": "<h1>Welcome to the Mock Responses example</h1>"
  127. }
  128. }
  129. ]
  130. }
  131. ```
  132. 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.
  133. ```json
  134. {
  135. "mocks": [
  136. {
  137. "route": "/two",
  138. "request": { "accepts": "xml" },
  139. "response": {
  140. "body": "<result id='2' name='whatever' />"
  141. }
  142. }
  143. ]
  144. }
  145. ```
  146. 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:
  147. ```json
  148. {
  149. "mocks": [
  150. {
  151. "route": "/three",
  152. "responses": [
  153. {
  154. "request": { "method": "GET" },
  155. "response": {
  156. "body": "<h1>Mock response for 'GET' request on /three</h1>"
  157. }
  158. },
  159. {
  160. "request": { "method": "POST" },
  161. "response": {
  162. "status": 400,
  163. "body": { "message": "That method is not allowed." }
  164. }
  165. }
  166. ]
  167. }
  168. ]
  169. }
  170. ```
  171. The examples above all returned static data. To define a **dynamic response**, create a mock module. Specify its path in the `module` property:
  172. ```json
  173. {
  174. "mocks": [
  175. {
  176. "route": "/four",
  177. "module": "/mocks/stream-self.js"
  178. }
  179. ]
  180. }
  181. ```
  182. Here's what the `stream-self` module looks like. The module should export a mock definition (an object with a `response` and optional `request`). In this example, the module simply streams itself to the response but you could craft and return *any* [valid value](https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1).
  183. ```js
  184. const fs = require('fs')
  185. module.exports = {
  186. response: {
  187. body: fs.createReadStream(__filename)
  188. }
  189. }
  190. ```
  191. For more power, define the response body 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.
  192. ```js
  193. const fs = require('fs')
  194. module.exports = {
  195. response: {
  196. body: function (ctx) {
  197. ctx.body = '<h1>I can do anything i want.</h1>'
  198. }
  199. }
  200. }
  201. ```
  202. If the route contains tokens, their values are passed to the response. For example, with this mock...
  203. ```json
  204. {
  205. "mocks": [
  206. {
  207. "route": "/five/:id",
  208. "module": "/mocks/example.js"
  209. }
  210. ]
  211. }
  212. ```
  213. ...the `id` value is passed to the body function. For example, a path of `/five/10?name=Lionel` would pass `10` to the body function. Additional, the value `Lionel` would be available on `ctx.query.name`:
  214. ```js
  215. const fs = require('fs')
  216. module.exports = {
  217. response: {
  218. body: function (ctx, id) {
  219. ctx.body = `<h1>id: ${id}, name: ${ctx.query.name}</h1>`
  220. }
  221. }
  222. }
  223. ```
  224. Here's an example of a REST collection (users). The config:
  225. ```json
  226. {
  227. "mocks": [
  228. {
  229. "route": "/users",
  230. "module": "/mocks/users.js"
  231. }
  232. ]
  233. }
  234. ```
  235. [Example](https://github.com/75lb/local-web-server/tree/master/example/mock).
  236. ### Stored config
  237. Use the same port and blacklist every time? Persist it to `package.json`:
  238. ```json
  239. {
  240. "name": "example",
  241. "version": "1.0.0",
  242. "local-web-server": {
  243. "port": 8100,
  244. "forbid": "*.json"
  245. }
  246. }
  247. ```
  248. or `.local-web-server.json`
  249. ```json
  250. {
  251. "port": 8100,
  252. "forbid": "*.json"
  253. }
  254. ```
  255. 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. Command-line options take precedence over all.
  256. To inspect stored config, run:
  257. ```sh
  258. $ ws --config
  259. ```
  260. ### Logging
  261. By default, local-web-server outputs a simple, dynamic statistics view. To see traditional web server logs, use `--log-format`:
  262. ```sh
  263. $ ws --log-format combined
  264. serving at http://localhost:8000
  265. ::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"
  266. ```
  267. The format value supplied is passed directly to [morgan](https://github.com/expressjs/morgan). The exception is `--log-format none` which disables all output.
  268. ### Access Control
  269. By default, access to all files is allowed (including dot files). Use `--forbid` to establish a blacklist:
  270. ```sh
  271. $ ws --forbid '*.json' '*.yml'
  272. serving at http://localhost:8000
  273. ```
  274. [Example](https://github.com/75lb/local-web-server/tree/master/example/forbid).
  275. ### Other usage
  276. #### Debugging
  277. Prints information about loaded middleware, arguments, remote proxy fetches etc.
  278. ```sh
  279. $ ws --verbose
  280. ```
  281. #### Compression
  282. Serve gzip-compressed resources, where applicable
  283. ```sh
  284. $ ws --compress
  285. ```
  286. #### Disable caching
  287. Disable etag response headers, forcing resources to be served in full every time.
  288. ```sh
  289. $ ws --no-cache
  290. ```
  291. #### mime-types
  292. 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:
  293. ```json
  294. {
  295. "mime": {
  296. "text/plain": [ "php", "pl" ]
  297. }
  298. }
  299. ```
  300. [Example](https://github.com/75lb/local-web-server/tree/master/example/mime-override).
  301. #### Log Visualisation
  302. 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).
  303. ## Install
  304. Ensure [node.js](http://nodejs.org) is installed first. Linux/Mac users may need to run the following commands with `sudo`.
  305. ```sh
  306. $ npm install -g local-web-server
  307. ```
  308. This will install the `ws` tool globally. To see the available options, run:
  309. ```sh
  310. $ ws --help
  311. ```
  312. ## Distribute with your project
  313. The standard convention with client-server applications is to add an `npm start` command to launch the server component.
  314. 1\. Install the server as a dev dependency
  315. ```sh
  316. $ npm install local-web-server --save-dev
  317. ```
  318. 2\. Add a `start` command to your `package.json`:
  319. ```json
  320. {
  321. "name": "example",
  322. "version": "1.0.0",
  323. "local-web-server": {
  324. "port": 8100,
  325. "forbid": "*.json"
  326. },
  327. "scripts": {
  328. "start": "ws"
  329. }
  330. }
  331. ```
  332. 3\. Document how to build and launch your site
  333. ```sh
  334. $ npm install
  335. $ npm start
  336. serving at http://localhost:8100
  337. ```
  338. ## API Reference
  339. * [local-web-server](#module_local-web-server)
  340. * [localWebServer([options])](#exp_module_local-web-server--localWebServer) ⇒ <code>[KoaApplication](https://github.com/koajs/koa/blob/master/docs/api/index.md#application)</code>
  341. * [~rewriteRule](#module_local-web-server--localWebServer..rewriteRule)
  342. <a name="exp_module_local-web-server--localWebServer"></a>
  343. ### localWebServer([options]) ⇒ <code>[KoaApplication](https://github.com/koajs/koa/blob/master/docs/api/index.md#application)</code> ⏏
  344. Returns a Koa application you can launch or mix into an existing app.
  345. **Kind**: Exported function
  346. **Params**
  347. - [options] <code>object</code> - options
  348. - [.static] <code>object</code> - koa-static config
  349. - [.root] <code>string</code> <code> = &quot;.&quot;</code> - root directory
  350. - [.options] <code>string</code> - [options](https://github.com/koajs/static#options)
  351. - [.serveIndex] <code>object</code> - koa-serve-index config
  352. - [.path] <code>string</code> <code> = &quot;.&quot;</code> - root directory
  353. - [.options] <code>string</code> - [options](https://github.com/expressjs/serve-index#options)
  354. - [.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).
  355. - [.spa] <code>string</code> - specify an SPA file to catch requests for everything but static assets.
  356. - [.log] <code>object</code> - [morgan](https://github.com/expressjs/morgan) config
  357. - [.format] <code>string</code> - [log format](https://github.com/expressjs/morgan#predefined-formats)
  358. - [.options] <code>object</code> - [options](https://github.com/expressjs/morgan#options)
  359. - [.compress] <code>boolean</code> - Serve gzip-compressed resources, where applicable
  360. - [.mime] <code>object</code> - A list of mime-type overrides, passed directly to [mime.define()](https://github.com/broofa/node-mime#mimedefine)
  361. - [.rewrite] <code>[Array.&lt;rewriteRule&gt;](#module_local-web-server--localWebServer..rewriteRule)</code> - One or more rewrite rules
  362. - [.verbose] <code>boolean</code> - Print detailed output, useful for debugging
  363. **Example**
  364. ```js
  365. const localWebServer = require('local-web-server')
  366. localWebServer().listen(8000)
  367. ```
  368. <a name="module_local-web-server--localWebServer..rewriteRule"></a>
  369. #### localWebServer~rewriteRule
  370. The `from` and `to` routes are specified using [express route-paths](http://expressjs.com/guide/routing.html#route-paths)
  371. **Kind**: inner typedef of <code>[localWebServer](#exp_module_local-web-server--localWebServer)</code>
  372. **Properties**
  373. | Name | Type | Description |
  374. | --- | --- | --- |
  375. | from | <code>string</code> | request route |
  376. | to | <code>string</code> | target route |
  377. **Example**
  378. ```json
  379. {
  380. "rewrite": [
  381. { "from": "/css/*", "to": "/build/styles/$1" },
  382. { "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
  383. { "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
  384. ]
  385. }
  386. ```
  387. * * *
  388. &copy; 2015 Lloyd Brookes <75pound@gmail.com>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).