Node.js 文件系统流pipe到Http响应流中
生活随笔
收集整理的這篇文章主要介紹了
Node.js 文件系统流pipe到Http响应流中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 內置http模塊,提供了http服務器和客戶端功能(path模塊也是內置模塊,而mime是附加模塊)
var http=require("http");
var fs=require("fs");
var _dirname="./html"// 創建服務器,創建HTTP服務器要調用http.createServer()函數,它只有一個參數,是個回調函數,服務器每次收到http請求后都會調用這個回調函數。服務器每收到一條http請求,都會用新的request和response對象觸發請求函數。
var server=http.createServer(function(req,resp){console.log("請求地址是:"+req.url); if('GET'==req.method && '/images'==req.url.substr(0,7) && '.jpg'==req.url.substr(-4)){fs.stat(_dirname+req.url,function(err,stat){if(err || !stat.isFile()){resp.writeHead(404);resp.end('File not found');return;}serve(_dirname+req.url,'application/jpg');});}else if('GET'==req.method && '/'==req.url){serve(_dirname+'/index.html','application/html');}else{resp.writeHead(404);resp.end('Unrecongnized cmd');return;}function serve(path,type){// 告訴瀏覽器發送什么樣的資源resp.writeHead(200,{"Content-Type":type});fs.createReadStream(path).pipe(resp);}
});// 服務器開始運作監聽端口
server.listen(3000,"localhost",function(){console.log("服務器開始運作,監聽端口3000中...");
});
?
轉載于:https://www.cnblogs.com/xiandedanteng/p/7531609.html
總結
以上是生活随笔為你收集整理的Node.js 文件系统流pipe到Http响应流中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 银行卡被锁了还能转账吗
- 下一篇: 理解Tomcat架构、启动流程及其性能优