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.

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