Node.js學(xué)習(xí)之路day3

1.只會(huì)helloworld的服務(wù)器

http模塊提供了request對(duì)象和response對(duì)象。
request對(duì)象封裝了http請(qǐng)求,通過(guò)調(diào)用request對(duì)象的屬性和方法,可以拿到http請(qǐng)求相關(guān)的信息。
response對(duì)象封裝了http響應(yīng),操作response對(duì)象的方法可以返回http響應(yīng)。
一個(gè)簡(jiǎn)單的helloworld栗子

let http=require('http')
//創(chuàng)建服務(wù)器對(duì)象
let server=http.createServer(function(request,response){
    console.log('first node server')
    //http響應(yīng)200
    response.writeHead(200,{'content-Type':'text/html'})
    //響應(yīng)內(nèi)容為helloworld
    response.write('<p>helloworld</p>')
    response.end()
})
server.listen(8080)

終端使用node test.js命令運(yùn)行,打開(kāi)瀏覽器localhost:8080

image.png

2.可返回文檔的服務(wù)器

可以解析請(qǐng)求中得url,從url分析到對(duì)應(yīng)的文件名,將本地的對(duì)應(yīng)文件返回即可
這里需要引入url模塊,path模塊,以及前兩篇博客里的fs模塊
代碼及注釋如下

let http=require('http')
let fs=require('fs')
let url=require('url')
let path=require('path')
let server=http.createServer(function(request,response){
   let p=url.parse(request.url).pathname   //獲得url中的文件路徑
   let root = path.resolve(process.argv[2] || '.');//獲得當(dāng)前目錄的路徑
   let currentPath=root+p  //拼接路徑
   fs.stat(currentPath,function(err,stat){
     if(!err&&stat.isFile()){   //沒(méi)有出錯(cuò)并且文件存在
       response.writeHead(200)
       fs.createReadStream(currentPath).pipe(response)  //以管道流形式傳輸給response
     }else{
       response.writeHead(404)
       response.end('<p>404</p>')
     }
   })
})
server.listen(8080)

讀取txt

image.png

讀取html

image.png

404

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

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

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