搭建一個nodejs專案 使用express
阿新 • • 發佈:2019-01-06
初始化專案
新建一個資料夾,執行 npm init
初始化專案
mkdir wqs_node
cd wqs_node
npm init
按照提示輸入一些專案的相關資訊
D:\web\node>cd wqs_node
D:\web\node\wqs_node>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (okadaGo)
Sorry, name can no longer contain capital letters.
name: (okadaGo) okada_go
version : (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\web\node\okadaGo\package.json:
{
"name": "wqs_node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes)
D:\web\node\wqs_node>
目錄結構
建立三個資料夾:public、routes 和 views。
專案的檔案結構如下
├─models/
├─public/
├─routes/
├─views/
├─index.js
└─package.json
對應檔案及資料夾的用處:
models
存放操作資料庫的檔案public
存放靜態檔案,如 css、圖片等routes
存放路由檔案views
存放模板檔案index.js
程式主檔案package.json
儲存專案的資訊,比如專案名、描述、作者、依賴等
安裝依賴
安裝 express 框架
npm install express --save
啟動專案
進入專案的根目錄,建立一個 index.js
檔案,並加入如下程式碼
var express = require('express');
var app = express();
app.get('/', function(res, rep) {
rep.send('Hello, word!');
});
app.listen(3000);
然後在控制檯中輸入
node index.js