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.

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