欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

nodejs搭建本地服務器并訪問文件的方法

 更新時間:2017年03月03日 09:01:50   作者:xqnode  
本篇文章主要介紹了nodejs搭建本地服務器并訪問文件的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

安裝node:https://nodejs.org/en/download/

在本地建立目錄:f:/nodetest,在該目錄下新建index.html作為我們將要訪問的內(nèi)容。新建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字符串轉(zhuǎn)換成對象并返回,通過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為文件路徑
    第二個參數(shù)為回調(diào)函數(shù)
      回調(diào)函數(shù)的一參為讀取錯誤返回的信息,返回空就沒有錯誤
      二參為讀取成功返回的文本內(nèi)容
    */
    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); //監(jiān)聽端口
console.log('服務成功開啟')

結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論