Express是目前最流行的基于Node.js的Web開(kāi)發(fā)框架,可以快速地搭建一個(gè)完整功能的網(wǎng)站。
$ mkdir hello-world //新建一個(gè)項(xiàng)目目錄
$ cd ./hello-world/ //進(jìn)入目錄
$ npm init -y //新建一個(gè)package.json文件
//package.json文件
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "4.x"
}
}
上面代碼定義了項(xiàng)目的名稱(chēng)、描述、版本等,并且指定需要4.0版本以上的Express。
$ npm install //安裝express
$ touch index.js //新建一個(gè)啟動(dòng)文件,假定叫做index.js
ps:現(xiàn)在我們是簡(jiǎn)單的demo,生成動(dòng)態(tài)網(wǎng)頁(yè)。
// index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.listen(3000);
$ node index //運(yùn)行啟動(dòng)腳本,在瀏覽器中訪問(wèn)項(xiàng)目網(wǎng)站
本機(jī)的3000端口

demo.png
退出:ctrl+c
ps:官網(wǎng)學(xué)習(xí)http://javascript.ruanyifeng.com/nodejs/express.html#toc4:use是express注冊(cè)中間件的方法,它返回一個(gè)函數(shù)。
//package.json文件
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
可以訪問(wèn)http://localhost:8080,它會(huì)在瀏覽器中打開(kāi)當(dāng)前目錄的public子目錄(嚴(yán)格來(lái)說(shuō),是打開(kāi)public目錄的index.html文件)。如果public目錄之中有一個(gè)圖片文件my_image.png,那么可以用http://localhost:8080/my_image.png訪問(wèn)該文件。