nodejs搭建本地服務(wù)器并訪問文件

安裝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 = 8080; //訪問端口號8080   //端口號最好為6000以上
var http = require('http'); //引入http模塊
var fs = require('fs'); //引入fs模塊
var url = require('url');//引入url模塊
var path = require('path');//引入path模塊

// req : 從瀏覽器帶來的請求信息
// res : 從服務(wù)器返回給瀏覽器的信息
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('C:/Users/Administrator/Desktop/html/node.js/index.html',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;charset="utf-8"'
            });
            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('服務(wù)成功開啟');

cmd下開啟服務(wù):

$ node server.js

結(jié)果:


image.png

--------------------- 本文來自 xqnode 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/xqnode/article/details/59526075?utm_source=copy

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容