OSDN Git Service

Regular updates
[twpd/master.git] / camp.md
1 ---
2 title: Camp
3 layout: 2017/sheet
4 category: JavaScript libraries
5 updated: 2017-09-21
6 weight: -1
7 intro: |
8   [Camp](https://github.com/espadrine/sc/) is a Node.js web server framework. This guide targets Camp v17.x.
9 ---
10
11 Getting started
12 ---------------
13 {: .-three-column}
14
15 ### Quick start
16 {: .-prime}
17
18 #### app.js
19 {: .-file}
20
21 ```js
22 const Camp = require('camp')
23 const camp = Camp.start({ port: 1234 })
24 ```
25
26 #### web/index.html
27 {: .-file}
28
29 ```html
30 <!doctype html>
31 <body>Hello world!</body>
32 ```
33
34 Camp serves files in `web/` by default.
35
36 ### Routes
37
38 #### Handles `/search?q=rainbows`
39
40 ```js
41 camp.path('/search', (req, res) => {
42   const q = res.query.q
43   res.json({ results: ··· })
44 })
45 ```
46 {: data-line="2"}
47
48 Also available: `camp.post`, `camp.get`.
49
50 ### Templates
51
52 ```js
53 const tpl = Camp.template('./templates/post.html')
54
55 camp.path('/blog/:post.html', (req, res) => {
56   res.template({
57     text: 'Hello world'
58   }, tpl)
59 })
60 ```
61 {: data-line="1,4"}
62
63 See: [Templates](https://github.com/espadrine/sc/blob/master/doc/Readme.md#templates)
64
65 ### Not found
66
67 ```js
68 camp.notFound('/*.lol', (req, res) => {
69   res.file('/404.html')
70 })
71 ```
72 {: data-line="1"}
73
74 See: [Fall through](https://github.com/espadrine/sc/blob/master/doc/Readme.md#fall-through)
75
76 ### Low level handler
77
78 ```js
79 camp.handle((req, res, next) => {
80   res.setHeader('X-Hello', 'world')
81   next()
82 })
83 ```
84 {: data-line="1"}
85
86 See: [Handlers](https://github.com/espadrine/sc/blob/master/doc/Readme.md#handlers)
87
88 Templates
89 ---------
90
91 ### Basic templates
92
93 ```js
94 const tpl = Camp.template('/templates/post.html')
95
96 camp.path('/blog/:post.html', (req, res) => {
97   res.template({
98     text: 'Hello world'
99   }, tpl)
100 })
101 ```
102 {: data-line="1,4,5,6"}
103
104 ### Implicit templates
105
106 ```js
107 camp.path('blog.html')
108 ```
109
110 Uses `blog.html` as a template.
111
112 See: [Templates](https://github.com/espadrine/sc/blob/master/doc/Readme.md#templates)
113
114 Advanced features
115 -----------------
116
117 ### Web sockets
118
119 ```js
120 camp.ws('/path', (socket) => { ··· })
121 ```
122
123 ```js
124 camp.wsChannels[path]
125 ```
126
127 ```js
128 camp.wsBroadcast('/path', (req, res) => {
129 })
130 ```
131
132 Sorry I don't completely understand this yet, but check it out in their docs.
133
134 See: [WebSocket](https://github.com/espadrine/sc/blob/master/doc/Readme.md#websocket)