aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html
blob: 3e556ada3a56f2a97e305eadff6a13c80419a015 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
---
title: Setting up a Node development environment
slug: Learn/Server-side/Express_Nodejs/development_environment
translation_of: Learn/Server-side/Express_Nodejs/development_environment
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}</div>

<p class="summary">現在你已經了解Express的目的了,接下來繼續說明如何設定和測試 Windows、Linux (Ubuntu)和Mac OS X上的Node/Express開發環境。不管你用的是什麼作業系統,你都能在本文中找到開發Express應用的入門需知。</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">前置需求:</th>
   <td>了解如何開啟terminal / command line. 了解如何在開發系統上安裝套件。</td>
  </tr>
  <tr>
   <th scope="row">目標:</th>
   <td>在你的電腦上設定Express(X.XX)開發環境。</td>
  </tr>
 </tbody>
</table>

<h2 id="Express_開發環境概覽">Express 開發環境概覽</h2>

<p>為了使你能快速的開發web應用,<em>Node</em> 和 <em>Express</em> 非常容易安裝,這個部分說明哪些工具是需要的、在Ubuntu、macOS和Windows中安裝Node和Express的最簡單方法、展示如何測試安裝成功與否。</p>

<h3 id="什麼是Express開發環境">什麼是Express開發環境?</h3>

<p><em>Express</em> 開發環境包含 <em>Nodejs、</em><em>NPM </em>套件管理器的安裝, 還有 <em>Express Application </em>產生器(可選)<em></em></p>

<p><em>Node </em>和 <em>NPM</em> 套件管理器會從準備好的 binary package、安裝檔、 作業系統的套件管理器或是從源檔一起安裝。接著 <em>Express </em>會透過 NPM 進行安裝,成為你所有個別 Express web 應用的依賴項(以及其他函式庫,如模板引擎,資料庫驅動程式,身份驗證中間層,用於提供靜態文件的中間件等)</p>

<p>NPM 也可用來安裝 Express 應用程式產生器(全域用),一個方便的工具幫助你創造符合 <a href="https://developer.mozilla.org/en-US/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture">MVC模式</a>的 Express web app 骨架。你不一定要使用應用程式產生器,因為每個Express應用程式不需要擁有同樣的檔案結構或依賴項。但為了專注於學習本身以及習慣模組化架構,我們會在接下來的教學中使用它。</p>

<div class="note">
<p><strong>注意:</strong> 與其他不包含單獨的web開發伺服器的Web框架不同。 在Node / Express中,Web應用程式創建並運行自己的Web伺服器!</p>
</div>

<p>典型的開發環境還包含其他工具,例如:編輯程式碼使用的<a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Available_text_editors">文字編輯器</a>、IDE,進行版本控置管理不同版本程式碼的<a href="/zh-TW/docs/Glossary/Git">Git</a>。這邊假設你已經有這種工具了(尤其是文字編輯器)</p>

<h3 id="哪些作業系統有支援">哪些作業系統有支援?</h3>

<p>Node 可以執行在 Windows、macOS、各種 Linux、Docker 等等(nodejs 的<a href="https://nodejs.org/en/download/">下載</a>頁面有完整的列表),在開發階段中個人電腦應該都有足夠的效能來執行 Node 。Express 執行在 Node 環境中,所以也能所有有安裝Node的平台上執行。</p>

<p>在這份教學中我們提供 Windows、macOS 和 Ubuntu Linux 的 Node 安裝教學。</p>

<h3 id="該用什麼版本的_NodeExpress">該用什麼版本的 Node/Express?</h3>

<p>Node 有許多<a href="https://nodejs.org/en/blog/release/">版本</a>,更新的版本代表著 bug 的修復、支援更新版本的 ECMAScript(JavaScript)標準和更好的 Node APIs 。</p>

<p>基本上你應該使用最新的 LTS 版本(<em>long-term supported,</em>長期維護版)。這種版本比『Current』版本更穩定而且還擁有最新的功能及持續性的更新維護。除非LTS不支援你需要的功能才使用『Current』版本。</p>

<p>而 Express ?永遠使用最新版!</p>

<h3 id="關於資料庫和其他依賴項呢">關於資料庫和其他依賴項呢?</h3>

<p>諸如資料庫、模版引擎、驗證引擎等等都屬於應用程式的一部分,這些依賴項會透過NPM導入應用程式環境中,在後續的章節將會進一步探討。</p>

<h2 id="安裝Node">安裝Node</h2>

<p>為了使用Express,首先要在你的電腦上安裝Node和<a href="https://docs.npmjs.com/">Node Package Manager (NPM)</a>。接下來用最簡單的方法在 Ubuntu Linux 16.04、 macOS和 Windows 10上安裝Nodejs的 Long Term Supported (LTS)版本吧</p>

<div class="note">
<p>以下的部分用最簡單的方法在上述的作業系統中安裝Node和NPM。如果你使用其他作業系統或想看看其他平台的安裝方式,請查閱<a href="https://nodejs.org/en/download/package-manager/">透過套件管理器安裝Node.js</a> (nodejs.org)。</p>
</div>

<h3 id="Windows_和macOS">Windows 和macOS</h3>

<p>直接使用安裝檔吧!</p>

<ol>
 <li>下載需要的安裝檔:
  <ol>
   <li>開啟 <a href="https://nodejs.org/en/">https://nodejs.org/en/</a></li>
   <li>對於大部分的使用者來說,直接下載LTS版本</li>
  </ol>
 </li>
 <li>下載完成後雙擊安裝檔,並照著安裝流程繼續。</li>
</ol>

<h3 id="Ubuntu_16.04">Ubuntu 16.04</h3>

<p>安裝Node 8.x LTS版本最簡單的方法是使用<a href="https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions">套件管理器</a>,只要在terminal上執行兩行指令</p>

<pre class="brush: bash notranslate"><code>curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs</code>

</pre>

<div class="warning">
<p><strong>警告:</strong> 不要直接從普通的Ubuntu repositories 安裝,那邊只有很舊的版本。</p>
</div>

<ol>
</ol>

<h3 id="測試_Nodejs_和NPM_的安裝">測試 Nodejs 和NPM 的安裝</h3>

<p>測試Node安裝最簡單的方法是在terminal/command上執行"version"這個指令,它會顯示當前的Node版本:</p>

<pre class="brush: bash notranslate">&gt;node -v
v8.9.4</pre>

<p>NPM應該會隨著Node一起安裝,可以用相同的方法進行測試:</p>

<pre class="brush: bash notranslate">&gt;npm -v
5.6.0</pre>

<p>接著用稍為令人興奮的方法來測試吧!讓我們創件一個非常基本的『純Node』伺服器,當你開啟正確的網頁時它會在瀏覽器上顯示"Hello World"</p>

<ol>
 <li>複製以下的文字到名為<strong>hellonode.js</strong>的檔案中,目前我們只用到Node而已。

  <pre class="brush: js notranslate">//載入HTTP模組
var http = require("http");

//創建HTTP 伺服器並監聽8000埠
http.createServer(function (request, response) {

   // Set the response HTTP header with HTTP status and Content type
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body "Hello World"
   response.end('Hello World\n');
}).listen(8000);

// Print URL for accessing server
console.log('Server running at http://127.0.0.1:8000/')
</pre>

  <p>這段程式載入『http』模組,並創建一個伺服器 (<code>createServer()</code>,並在8000埠上監聽HTTP requests。 The script then prints a message to the console about what browser URL you can use to test the server. The <code>createServer()</code> function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".</p>
 </li>
 <li>
  <div class="note">
  <p><strong>Note:</strong>  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!</p>
  </div>
 </li>
 <li>Start the server by navigating into the same directory as your <code>hellonode.js</code> file in your command prompt, and calling <code>node</code> along with the script name, like so:
  <pre class="brush: bash notranslate">&gt;node hellonode.js
Server running at http://127.0.0.1:8000/
</pre>
 </li>
 <li>Navigate to the URL (<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>). If everything is working, the browser should simply display the string "Hello World".</li>
</ol>

<h2 id="Using_NPM">Using NPM</h2>

<p>Next to <em>Node</em> itself, <a href="https://docs.npmjs.com/">NPM</a> is the most important tool for working with<em> Node </em>applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. </p>

<div class="note">
<p><strong>Note:</strong> From Node's perspective, <em>Express</em> is just another package that you need to install using NPM and then require in your own code.</p>
</div>

<p>You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named <a href="https://docs.npmjs.com/files/package.json">package.json</a>. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of <em>Node</em> it can work with, etc. The <strong>package.json</strong> file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).</p>

<h3 id="Adding_dependencies">Adding dependencies</h3>

<p>The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.</p>

<div class="note">
<p><strong>Note:</strong> Here we show the instructions to fetch and install the <em>Express</em> package. Later on we'll show how this package, and others, are already specified for us using the <em>Express Application Generator</em>. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.</p>
</div>

<ol>
 <li>First create a directory for your new application and navigate into it:
  <pre class="brush: bash notranslate">mkdir myapp
cd myapp</pre>
 </li>
 <li>Use the npm <code>init</code> command to create a <strong>package.json</strong> file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is <strong>index.js</strong>). For now, just accept the defaults:
  <pre class="brush: bash notranslate">npm init</pre>

  <p>If you display the <strong>package.json</strong> file (<code>cat package.json</code>), you will see the defaults that you accepted, ending with the license.</p>

  <pre class="brush: json notranslate">{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "",
  "license": "ISC"
}
</pre>
 </li>
 <li>Now install the <em>Express</em> library in the <strong>myapp</strong> directory. The package will automatically be saved to the dependencies list in your <strong>package.json</strong> file.
  <pre class="brush: bash notranslate">npm install express</pre>

  <p>The dependencies section of your <strong>package.json</strong> will now appear at the end of the <strong>package.json</strong> file and will include <em>Express</em>.</p>

  <pre class="brush: json notranslate">{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "",
  "license": "ISC",
<strong>  "dependencies": {
    "express": "^4.16.2"
  }</strong>
}
</pre>
 </li>
 <li>To use the library you call the <code>require()</code> function as shown below.
  <pre class="notranslate"><code><strong>var express = require('express')</strong>
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(</code>8000<code>, function () {
  console.log('Example app listening on port </code>8000<code>!')
})</code>
</pre>

  <p>This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (<code>app</code>) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The <code>app.get()</code> function only responds to HTTP <code>GET</code> requests with the specified URL path ('/'), in this case by calling a function to send our <em>Hello World!</em> message. <br>
   <br>
   Create a file named <strong>index.js</strong> in the root of the "myapp" application directory and give it the contents shown above.</p>
 </li>
 <li>You can start the server by calling node with the script in your command prompt:
  <pre class="brush: bash notranslate">&gt;node index.js
Example app listening on port 8000
</pre>
 </li>
 <li>Navigate to the URL (<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>). If everything is working, the browser should simply display the string "Hello World!".</li>
</ol>

<h3 id="Development_dependencies">Development dependencies</h3>

<p>If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool <a href="http://eslint.org/">eslint</a> you would call NPM as shown:</p>

<pre class="brush: bash notranslate"><code>npm install eslint --save-dev</code></pre>

<p>The following entry would then be added to your application's <strong>package.json</strong>:</p>

<pre class="brush: js notranslate">  "devDependencies": {
    "eslint": "^4.12.1"
  }
</pre>

<div class="note">
<p><strong>Note:</strong> "<a href="https://en.wikipedia.org/wiki/Lint_(software)">Linters</a>" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.</p>
</div>

<h3 id="Running_tasks">Running tasks</h3>

<p>In addition to defining and fetching dependencies you can also define <em>named</em> scripts in your <strong>package.json</strong> files and call NPM to execute them with the <a href="https://docs.npmjs.com/cli/run-script">run-script</a> command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).</p>

<div class="note">
<p><strong>Note:</strong> Task runners like <a href="http://gulpjs.com/">Gulp</a> and <a href="http://gruntjs.com/">Grunt</a> can also be used to run tests and other external tools.</p>
</div>

<p>For example, to define a script to run the <em>eslint</em> development dependency that we specified in the previous section we might add the following script block to our <strong>package.json</strong> file (assuming that our application source is in a folder /src/js):</p>

<pre class="brush: js notranslate">"scripts": {
  ...
  "lint": "eslint src/js"
  ...
}
</pre>

<p>To explain a little further, <code>eslint src/js</code> is a command that we could enter in our terminal/command line to run <code>eslint</code> on JavaScript files contained in the <code>src/js</code> directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — <code>lint</code>.</p>

<p>We would then be able to run <em>eslint</em> using NPM by calling:</p>

<pre class="brush: bash notranslate"><code>npm run-script lint
# OR (using the alias)
npm run lint</code>
</pre>

<p>This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.</p>

<h2 id="Installing_the_Express_Application_Generator">Installing the Express Application Generator</h2>

<p>The <a href="https://expressjs.com/en/starter/generator.html">Express Application Generator</a> tool generates an Express application "skeleton". Install the generator using NPM as shown (the <code>-g</code> flag installs the tool globally so that you can call it from anywhere):</p>

<pre class="notranslate"><code>npm install express-generator -g</code></pre>

<p>To create an <em>Express</em> app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:</p>

<pre class="brush: bash notranslate">express helloworld</pre>

<div class="note">
<p><strong>Note: </strong>You can also specify the template library to use and a number of other settings. Use the <code>help</code> command to see all the options:</p>

<pre class="brush: bash notranslate">express --help
</pre>
</div>

<p>NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.</p>

<div class="note">
<p>The new app will have a <strong>package.json</strong> file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:</p>

<pre class="brush: js notranslate">{
  "name": "helloworld",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "jade": "~1.11.0",
    "morgan": "~1.9.0",
    "serve-favicon": "~2.4.5"
  }
}</pre>
</div>

<p>Install all the dependencies for the helloworld app using NPM as shown:</p>

<pre class="brush: bash notranslate">cd helloworld
npm install
</pre>

<p>Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:</p>

<pre class="brush: bash notranslate"># Run the helloworld on Windows
SET DEBUG=helloworld:* &amp; npm start

# Run helloworld on Linux/macOS
DEBUG=helloworld:* npm start
</pre>

<p>The DEBUG command creates useful logging, resulting in an output like that shown below.</p>

<pre class="brush: bash notranslate">&gt;SET DEBUG=helloworld:* &amp; npm start

&gt; helloworld@0.0.0 start D:\Github\expresstests\helloworld
&gt; node ./bin/www

  helloworld:server Listening on port 3000 +0ms</pre>

<p>Open a browser and navigate to <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a> to see the default Express welcome page.</p>

<p><img alt="Express - Generated App Default Screen" src="https://mdn.mozillademos.org/files/14331/express_default_screen.png" style="border-style: solid; border-width: 1px; display: block; height: 301px; margin: 0px auto; width: 675px;"></p>

<p>We'll talk more about the generated app when we get to the article on generating a skeleton application.</p>

<ul>
</ul>

<h2 id="總結">總結</h2>

<p>你現在有一個 Node 開發環境在你的電腦上運行,可以用來創造 Express 網頁應用。你也看到如何用 NPM 來加載 Express到一個應用中,以及看到如何使用 Express 應用產生器,創建應用,然後執行它們。</p>

<p>下一篇文章,我們開始跟著教程一步一步實作,使用這個開發環境與搭配工具,建立一個完整的網頁應用。</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="https://nodejs.org/en/download/">Downloads</a> page (nodejs.org)</li>
 <li><a href="https://nodejs.org/en/download/package-manager/">Installing Node.js via package manager</a> (nodejs.org)</li>
 <li><a href="http://expressjs.com/en/starter/installing.html">Installing Express</a> (expressjs.com)</li>
 <li><a href="https://expressjs.com/en/starter/generator.html">Express Application Generator</a> (expressjs.com)</li>
</ul>

<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}</p>



<h2 id="In_this_module">In this module</h2>

<ul>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li>
 <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li>
</ul>