1.只會helloworld的服務(wù)器
http模塊提供了request對象和response對象。
request對象封裝了http請求糟秘,通過調(diào)用request對象的屬性和方法,可以拿到http請求相關(guān)的信息。
response對象封裝了http響應(yīng)克滴,操作response對象的方法可以返回http響應(yīng)泊窘。
一個簡單的helloworld栗子
let http=require('http')
//創(chuàng)建服務(wù)器對象
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命令運行熄驼,打開瀏覽器localhost:8080
image.png
2.可返回文檔的服務(wù)器
可以解析請求中得url,從url分析到對應(yīng)的文件名烘豹,將本地的對應(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] || '.');//獲得當前目錄的路徑
let currentPath=root+p //拼接路徑
fs.stat(currentPath,function(err,stat){
if(!err&&stat.isFile()){ //沒有出錯并且文件存在
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