1. 程式人生 > >node.js學習筆記(2)--使用Express快速建立應用

node.js學習筆記(2)--使用Express快速建立應用

1.安裝express應用生成器

開啟cmd 鍵入如下程式碼
$npm install express-generator -g   #全域性安裝
安裝成功如下-----

2.express命令

開啟cmd 鍵入$express -h 顯示所有可用的命令列選項
C:\Users\Administrator>express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sas
s) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

3.生成應用

在E盤新建一個資料夾test 開啟命令視窗  鍵入 $express first -e  該命令的意思是:在當前目錄下建立first資料夾 建立一個ejs模板的應用(如果不輸入 -e 則生成預設的jade模板)
E:\test>express first -e

   create : first
   create : first/package.json
   create : first/app.js
   create : first/public
   create : first/public/javascripts
   create : first/public/images
   create : first/routes
   create : first/routes/index.js
   create : first/routes/users.js
   create : first/views
   create : first/views/index.ejs
   create : first/views/error.ejs
   create : first/public/stylesheets
   create : first/public/stylesheets/style.css
   create : first/bin
   create : first/bin/www

   install dependencies:
     > cd first && npm install

   run the app:
     > SET DEBUG=first:* & npm start

完成後資料夾顯示如下 
然後鍵入命令
$cd first         #進入first資料夾
$npm install      #安裝依賴包
  安裝完成後會發現多了個node_modules資料夾 裡面放的就是我們安裝的模組
注: app.js:啟動檔案,專案的入口
package.json:儲存專案的資訊及模組依賴,當在 dependencies 中新增依賴的模組時,執行npm install,npm 會檢查當前目錄下的 package.json,並自動安裝所有依賴模組
node_modules:存放 package.json 中安裝的模組,當你在 package.json 新增依賴的模組並安裝後,存放在這個資料夾下

public:存放 image、css、js 等檔案
routes:存放路由檔案
views:存放檢視檔案或者說模版檔案
bin:存放可執行檔案

4.啟動應用

鍵入命令$npm start 啟動成功如下:
E:\test\first>npm start


> [email protected] start E:\test\first
> node ./bin/www

5.訪問應用

然後在瀏覽器中開啟 http://localhost:3000/ 網址你可以看到welcome to Express,證明你已經成功了

其他