1. 程式人生 > >nodejs 中public資料夾作用初探

nodejs 中public資料夾作用初探

本篇部落格對比兩個nodejs例項,一個例項將index.html放在與index.js相同的資料夾下;而另一個例項則建立一個與index.js同級的public資料夾,index.html放在public中。第二個例項藉助語句

app.use(express.static(path.join(__dirname, 'public')));

把所有靜態資源(html檔案,或者css之類)指定放置到與入口檔案index.js同級的public資料夾下,同樣實現與例項1的效果。

例項一程式碼:

 index.js在package.json中被指定為入口檔案(相當於C語言的 main.cpp)

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    //res.send('hello!');
    res.sendFile(__dirname + '/index.html');
});

app.listen(8080);

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web管理平臺</title>
</head>
<body>
  <h1>Web管理平臺</h1>
</body>
</html>

當本地瀏覽器訪問127.0.0.1:8080時,index.js的sendFile()函式會把index.html發給瀏覽器。

 

再看第二個例項。index.js

此時index.html放到了public資料夾裡面

同時,index.js的app.use()函式也指定了public資料夾作為存放靜態資源的路徑。故sendFile()函式自動從public資料夾裡尋找html

var express = require('express');
var app = express();
var path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.sendFile('/index.html');
});

app.listen(8080);

例項2的效果: