nodejs搭建本地伺服器並訪問檔案
阿新 • • 發佈:2019-01-01
在本地建立目錄:f:/nodetest,在該目錄下新建index.html作為我們將要訪問的內容。新建server.js作為node開啟的入口:
$ cd f:/nodetest
$ mkdir index.html
$ mkdir server.js
index.html檔案裡簡單寫一點東西:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>node Test</title>
<style type ="text/css">
html,body{
margin: 0;
padding: 0;
}
.node{
width: 300px;
margin: 0 auto;
padding-top:100px;
text-align: center;
}
.node h1{
color:rgb(33,199,40);
}
</style >
</head>
<body>
<div class="node">
<h1>Hello Nodejs</h1>
</div>
</body>
</html>
接下來寫server.js:
const PORT = 8888; //訪問埠號8888 //埠號最好為6000以上
var http = require('http'); //引入http模組
var fs = require('fs'); //引入fs模組
var url = require('url');//引入url模組
var path = require('path');//引入path模組
// req : 從瀏覽器帶來的請求資訊
// res : 從伺服器返回給瀏覽器的資訊
var server = http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname;;
//客戶端輸入的url,例如如果輸入localhost:8888/index.html,那麼這裡的url == /index.html
//url.parse()方法將一個URL字串轉換成物件並返回,通過pathname來訪問此url的地址。
var realPath = path.join('F:/nodejs/nodetest',pathname);
//完整的url路徑
console.log(realPath);
// F:/nodejs/nodetest/index.html
fs.readFile(realPath,function(err,data){
/*
realPath為檔案路徑
第二個引數為回撥函式
回撥函式的一參為讀取錯誤返回的資訊,返回空就沒有錯誤
二參為讀取成功返回的文字內容
*/
if(err){
//未找到檔案
res.writeHead(404,{
'content-type':'text/plain'
});
res.write('404,頁面不在');
res.end();
}else{
//成功讀取檔案
res.writeHead(200,{
'content-type':'text/html;charset="utf-8'
});
res.write(data);
res.end();
}
})
});
server.listen(PORT); //監聽埠
console.log('服務成功開啟')
cmd下開啟服務:
$ node server.js
結果: