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
19 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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. [![Join the chat at https://gitter.im/75lb/local-web-server](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/75lb/local-web-server?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
  7. ***Requires node v4.0.0 or higher. Install the [previous release](https://github.com/75lb/local-web-server/tree/prev) for older node support.***
  8. # local-web-server
  9. A simple web-server for productive front-end development. Typical use cases:
  10. * Front-end Development
  11. * Static or Single Page App development
  12. * Re-route paths to local or remote resources
  13. * Efficient, predictable, entity-tag-powered conditional request handling (no need to 'Disable Cache' in DevTools, slowing page-load down)
  14. * Bundle with your front-end project
  15. * Very little configuration, just a few options
  16. * Outputs a dynamic statistics view to the terminal
  17. * Configurable log output, compatible with [Goaccess, Logstalgia and glTail](https://github.com/75lb/local-web-server/blob/master/doc/visualisation.md)
  18. * Back-end service mocking
  19. * Prototype a web service, microservice, REST API etc.
  20. * Mocks are defined with config (static), or code (dynamic).
  21. * CORS-friendly, all origins allowed by default.
  22. * Proxy server
  23. * Map local routes to remote servers. Removes CORS pain when consuming remote services.
  24. * HTTPS server
  25. * HTTPS is strictly required by some modern techs (ServiceWorker, Media Capture and Streams etc.)
  26. * File sharing
  27. ## Synopsis
  28. local-web-server is a simple command-line tool. To use it, from your project directory run `ws`.
  29. <pre><code>$ ws --help
  30. <strong>local-web-server</strong>
  31. A simple web-server for productive front-end development.
  32. <strong>Synopsis</strong>
  33. $ ws [&lt;server options&gt;]
  34. $ ws --config
  35. $ ws --help
  36. <strong>Server</strong>
  37. -p, --port number Web server port.
  38. -d, --directory path Root directory, defaults to the current directory.
  39. -f, --log-format string If a format is supplied an access log is written to stdout. If
  40. not, a dynamic statistics view is displayed. Use a preset ('none',
  41. 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a
  42. custom format (e.g. ':method -> :url').
  43. -r, --rewrite expression ... A list of URL rewrite rules. For each rule, separate the 'from'
  44. and 'to' routes with '->'. Whitespace surrounded the routes is
  45. ignored. E.g. '/from -> /to'.
  46. -s, --spa file Path to a Single Page App, e.g. app.html.
  47. -c, --compress Serve gzip-compressed resources, where applicable.
  48. -b, --forbid path ... A list of forbidden routes.
  49. -n, --no-cache Disable etag-based caching -forces loading from disk each request.
  50. --key file SSL key. Supply along with --cert to launch a https server.
  51. --cert file SSL cert. Supply along with --key to launch a https server.
  52. --verbose Verbose output, useful for debugging.
  53. <strong>Misc</strong>
  54. -h, --help Print these usage instructions.
  55. --config Print the stored config.
  56. Project home: https://github.com/75lb/local-web-server
  57. </code></pre>
  58. ## Examples
  59. For the examples below, we assume we're in a project directory looking like this:
  60. ```sh
  61. .
  62. ├── css
  63. │   └── style.css
  64. ├── index.html
  65. └── package.json
  66. ```
  67. 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`.
  68. ### Static site
  69. Fire up your static site on the default port:
  70. ```sh
  71. $ ws
  72. serving at http://localhost:8000
  73. ```
  74. [Example](https://github.com/75lb/local-web-server/tree/master/example/simple).
  75. ### Single Page Application
  76. You're building a web app with client-side routing, so mark `index.html` as the SPA.
  77. ```sh
  78. $ ws --spa index.html
  79. ```
  80. 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:
  81. *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.*
  82. [Example](https://github.com/75lb/local-web-server/tree/master/example/spa).
  83. ### URL rewriting
  84. Your application requested `/css/style.css` but it's stored at `/build/css/style.css`. To avoid a 404 you need a rewrite rule:
  85. ```sh
  86. $ ws --rewrite '/css/style.css -> /build/css/style.css'
  87. ```
  88. Or, more generally (matching any stylesheet under `/css`):
  89. ```sh
  90. $ ws --rewrite '/css/:stylesheet -> /build/css/:stylesheet'
  91. ```
  92. With a deep CSS directory structure it may be easier to mount the entire contents of `/build/css` to the `/css` path:
  93. ```sh
  94. $ ws --rewrite '/css/* -> /build/css/$1'
  95. ```
  96. this rewrites `/css/a` as `/build/css/a`, `/css/a/b/c` as `/build/css/a/b/c` etc.
  97. #### Proxied requests
  98. If the `to` URL contains a remote host, local-web-server will act as a proxy - fetching and responding with the remote resource.
  99. Mount the npm registry locally:
  100. ```sh
  101. $ ws --rewrite '/npm/* -> http://registry.npmjs.org/$1'
  102. ```
  103. Map local requests for repo data to the Github API:
  104. ```sh
  105. $ ws --rewrite '/:user/repos/:name -> https://api.github.com/repos/:user/:name'
  106. ```
  107. [Example](https://github.com/75lb/local-web-server/tree/master/example/rewrite).
  108. ### Mock Responses
  109. 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.
  110. 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:
  111. ```json
  112. {
  113. "mocks": [
  114. {
  115. "route": "/",
  116. "response": {
  117. "body": "<h1>Welcome to the Mock Responses example</h1>"
  118. }
  119. }
  120. ]
  121. }
  122. ```
  123. 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):
  124. ```json
  125. {
  126. "mocks": [
  127. {
  128. "route": "/",
  129. "response": {
  130. "type": "text/plain",
  131. "body": "<h1>Welcome to the Mock Responses example</h1>"
  132. }
  133. }
  134. ]
  135. }
  136. ```
  137. #### Conditional Response
  138. 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.
  139. ```json
  140. {
  141. "mocks": [
  142. {
  143. "route": "/two",
  144. "request": { "accepts": "xml" },
  145. "response": {
  146. "body": "<result id='2' name='whatever' />"
  147. }
  148. }
  149. ]
  150. }
  151. ```
  152. #### Multiple Potential Responses
  153. 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:
  154. ```json
  155. {
  156. "mocks": [
  157. {
  158. "route": "/three",
  159. "responses": [
  160. {
  161. "request": { "method": "GET" },
  162. "response": {
  163. "body": "<h1>Mock response for 'GET' request on /three</h1>"
  164. }
  165. },
  166. {
  167. "request": { "method": "POST" },
  168. "response": {
  169. "status": 400,
  170. "body": { "message": "That method is not allowed." }
  171. }
  172. }
  173. ]
  174. }
  175. ]
  176. }
  177. ```
  178. #### Dynamic Response
  179. The examples above all returned static data. To define a dynamic response, create a mock module. Specify its path in the `module` property:
  180. ```json
  181. {
  182. "mocks": [
  183. {
  184. "route": "/four",
  185. "module": "/mocks/stream-self.js"
  186. }
  187. ]
  188. }
  189. ```
  190. 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).
  191. ```js
  192. const fs = require('fs')
  193. module.exports = {
  194. response: {
  195. body: fs.createReadStream(__filename)
  196. }
  197. }
  198. ```
  199. #### Response function
  200. 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.
  201. ```js
  202. module.exports = {
  203. response: function (ctx) {
  204. ctx.body = '<h1>I can do anything i want.</h1>'
  205. }
  206. }
  207. ```
  208. If the route contains tokens, their values are passed to the response. For example, with this mock...
  209. ```json
  210. {
  211. "mocks": [
  212. {
  213. "route": "/players/:id",
  214. "module": "/mocks/players.js"
  215. }
  216. ]
  217. }
  218. ```
  219. ...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`:
  220. ```js
  221. module.exports = {
  222. response: function (ctx, id) {
  223. ctx.body = `<h1>id: ${id}, name: ${ctx.query.name}</h1>`
  224. }
  225. }
  226. ```
  227. #### RESTful Resource example
  228. 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.
  229. ```json
  230. {
  231. "mocks": [
  232. { "route": "/users", "module": "/mocks/users.js" },
  233. { "route": "/users/:id", "module": "/mocks/user.js" }
  234. ]
  235. }
  236. ```
  237. Define a module (`users.json`) defining seed data:
  238. ```json
  239. [
  240. { "id": 1, "name": "Lloyd", "age": 40, "nationality": "English" },
  241. { "id": 2, "name": "Mona", "age": 34, "nationality": "Palestinian" },
  242. { "id": 3, "name": "Francesco", "age": 24, "nationality": "Italian" }
  243. ]
  244. ```
  245. The collection module:
  246. ```js
  247. const users = require('./users.json')
  248. /* responses for /users */
  249. const mockResponses = [
  250. /* Respond with 400 Bad Request for PUT and DELETE - inappropriate on a collection */
  251. { request: { method: 'PUT' }, response: { status: 400 } },
  252. { request: { method: 'DELETE' }, response: { status: 400 } },
  253. {
  254. /* for GET requests return a subset of data, optionally filtered on 'minAge' and 'nationality' */
  255. request: { method: 'GET' },
  256. response: function (ctx) {
  257. ctx.body = users.filter(user => {
  258. const meetsMinAge = (user.age || 1000) >= (Number(ctx.query.minAge) || 0)
  259. const requiredNationality = user.nationality === (ctx.query.nationality || user.nationality)
  260. return meetsMinAge && requiredNationality
  261. })
  262. }
  263. },
  264. {
  265. /* for POST requests, create a new user and return the path to the new resource */
  266. request: { method: 'POST' },
  267. response: function (ctx) {
  268. const newUser = ctx.request.body
  269. users.push(newUser)
  270. newUser.id = users.length
  271. ctx.status = 201
  272. ctx.response.set('Location', `/users/${newUser.id}`)
  273. }
  274. }
  275. ]
  276. module.exports = mockResponses
  277. ```
  278. The individual resource module:
  279. ```js
  280. const users = require('./users.json')
  281. /* responses for /users/:id */
  282. const mockResponses = [
  283. /* don't support POST here */
  284. { request: { method: 'POST' }, response: { status: 400 } },
  285. /* for GET requests, return a particular user */
  286. {
  287. request: { method: 'GET' },
  288. response: function (ctx, id) {
  289. ctx.body = users.find(user => user.id === Number(id))
  290. }
  291. },
  292. /* for PUT requests, update the record */
  293. {
  294. request: { method: 'PUT' },
  295. response: function (ctx, id) {
  296. const updatedUser = ctx.request.body
  297. const existingUserIndex = users.findIndex(user => user.id === Number(id))
  298. users.splice(existingUserIndex, 1, updatedUser)
  299. ctx.status = 200
  300. }
  301. },
  302. /* DELETE request: remove the record */
  303. {
  304. request: { method: 'DELETE' },
  305. response: function (ctx, id) {
  306. const existingUserIndex = users.findIndex(user => user.id === Number(id))
  307. users.splice(existingUserIndex, 1)
  308. ctx.status = 200
  309. }
  310. }
  311. ]
  312. module.exports = mockResponses
  313. ```
  314. [Example](https://github.com/75lb/local-web-server/tree/master/example/mock).
  315. ### HTTPS Server
  316. Some modern techs (ServiceWorker, any `MediaDevices.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:
  317. ```
  318. $ ws --key localhost.key --cert localhost.crt
  319. ```
  320. If you don't have a key and certificate it's trivial to create them. You do not need third-party verification (Verisign etc.) for development purposes. To get the green padlock in the browser, the certificate..
  321. * must have a `Common Name` value matching the FQDN of the server
  322. * must be verified by a Certificate Authority (but we can overrule this - see below)
  323. First create a certificate:
  324. 1. Install openssl.
  325. `$ brew install openssl`
  326. 2. Generate a RSA private key.
  327. `$ openssl genrsa -des3 -passout pass:x -out ws.pass.key 2048`
  328. 3. Create RSA key.
  329. ```
  330. $ openssl rsa -passin pass:x -in ws.pass.key -out ws.key
  331. ```
  332. 4. Create certificate request. The command below will ask a series of questions about the certificate owner. The most imporant answer to give is for `Common Name`, you can accept the default values for the others. **Important**: you **must** input your server's correct FQDN (`dev-server.local`, `laptop.home` etc.) into the `Common Name` field. The cert is only valid for the domain specified here. You can find out your computers host name by running the command `hostname`. For example, mine is `mba3.home`.
  333. `$ openssl req -new -key ws.key -out ws.csr`
  334. 5. Generate self-signed certificate.
  335. `$ openssl x509 -req -days 365 -in ws.csr -signkey ws.key -out ws.crt`
  336. 6. Clean up files we're finished with
  337. `$ rm ws.pass.key ws.csr`
  338. 7. Launch HTTPS server. In iTerm, control-click the first URL (with the hostname matching `Common Name`) to launch your browser.
  339. ```
  340. $ ws --key ws.key --cert ws.crt
  341. serving at https://mba3.home:8010, https://127.0.0.1:8010, https://192.168.1.203:8010
  342. ```
  343. Chrome and Firefox will still complain your certificate has not been verified by a Certificate Authority. Firefox will offer you an `Add an exception` option, allowing you to ignore the warning and manually mark the certificate as trusted. In Chrome on Mac, you can manually trust the certificate another way:
  344. 1. Open Keychain
  345. 2. Click File -> Import. Select the `.crt` file you created.
  346. 3. In the `Certificates` category, double-click the cert you imported.
  347. 4. In the `trust` section, underneath `when using this certificate`, select `Always Trust`.
  348. Now you have a valid, trusted certificate for development.
  349. ### Stored config
  350. Use the same options every time? Persist then to `package.json`:
  351. ```json
  352. {
  353. "name": "example",
  354. "version": "1.0.0",
  355. "local-web-server": {
  356. "port": 8100,
  357. "forbid": "*.json"
  358. }
  359. }
  360. ```
  361. or `.local-web-server.json`
  362. ```json
  363. {
  364. "port": 8100,
  365. "forbid": "*.json"
  366. }
  367. ```
  368. 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.
  369. To inspect stored config, run:
  370. ```sh
  371. $ ws --config
  372. ```
  373. ### Logging
  374. By default, local-web-server outputs a simple, dynamic statistics view. To see traditional web server logs, use `--log-format`:
  375. ```sh
  376. $ ws --log-format combined
  377. serving at http://localhost:8000
  378. ::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"
  379. ```
  380. The format value supplied is passed directly to [morgan](https://github.com/expressjs/morgan). The exception is `--log-format none` which disables all output.
  381. ### Access Control
  382. By default, access to all files is allowed (including dot files). Use `--forbid` to establish a blacklist:
  383. ```sh
  384. $ ws --forbid '*.json' '*.yml'
  385. serving at http://localhost:8000
  386. ```
  387. [Example](https://github.com/75lb/local-web-server/tree/master/example/forbid).
  388. ### Other usage
  389. #### Debugging
  390. Prints information about loaded middleware, arguments, remote proxy fetches etc.
  391. ```sh
  392. $ ws --verbose
  393. ```
  394. #### Compression
  395. Serve gzip-compressed resources, where applicable
  396. ```sh
  397. $ ws --compress
  398. ```
  399. #### Disable caching
  400. Disable etag response headers, forcing resources to be served in full every time.
  401. ```sh
  402. $ ws --no-cache
  403. ```
  404. #### mime-types
  405. 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:
  406. ```json
  407. {
  408. "mime": {
  409. "text/plain": [ "php", "pl" ]
  410. }
  411. }
  412. ```
  413. [Example](https://github.com/75lb/local-web-server/tree/master/example/mime-override).
  414. #### Log Visualisation
  415. 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).
  416. ## Install
  417. Ensure [node.js](http://nodejs.org) is installed first. Linux/Mac users may need to run the following commands with `sudo`.
  418. ```sh
  419. $ npm install -g local-web-server
  420. ```
  421. This will install the `ws` tool globally. To see the available options, run:
  422. ```sh
  423. $ ws --help
  424. ```
  425. ## Distribute with your project
  426. The standard convention with client-server applications is to add an `npm start` command to launch the server component.
  427. 1\. Install the server as a dev dependency
  428. ```sh
  429. $ npm install local-web-server --save-dev
  430. ```
  431. 2\. Add a `start` command to your `package.json`:
  432. ```json
  433. {
  434. "name": "example",
  435. "version": "1.0.0",
  436. "local-web-server": {
  437. "port": 8100,
  438. "forbid": "*.json"
  439. },
  440. "scripts": {
  441. "start": "ws"
  442. }
  443. }
  444. ```
  445. 3\. Document how to build and launch your site
  446. ```sh
  447. $ npm install
  448. $ npm start
  449. serving at http://localhost:8100
  450. ```
  451. ## API Reference
  452. {{#module name="local-web-server"}}
  453. {{>body~}}
  454. {{>member-index~}}
  455. {{>separator~}}
  456. {{>members~}}
  457. {{/module}}
  458. * * *
  459. &copy; 2015 Lloyd Brookes <75pound@gmail.com>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).