版權聲明:本文為原創文章,轉載請標明出處
一個簡單的html頁面:
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> 登錄頁面login <img src="./showimg" /> </body> </html>
在這里將通過路由的方式來讀取圖片和文字。
test8.js:
var http = require('http');
var url = require('url');
var router = require('./router')
http.createServer(function(request,response){
// response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
if(request.url!="/favicon.ico"){ //清除2次訪問
var pathname = url.parse(request.url).pathname;
pathname = pathname.replace(/\//,'');//替換掉前面的/
console.log(pathname);
router[pathname](request,response);
}
}).listen(8000);
console.log("is running")
邏輯是這樣的:在瀏覽器輸入127.0.0.1:8000/login,通過路由識別出login后,調用router.js中login的方法,在這里面去讀取login.html,然后再把內容發送回給客戶端。當客戶端識別到<img src=" "/>時,又會再次發送一個請求到server(服務端),將src里的路由提交到router.js里,服務端接着去讀取圖片,將圖片以二進制流的方式發送給瀏覽器。
router.js:
var optfile = require('./optfile');
function getRecall(req,res){
res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
function recall(data){
res.write(data);
res.end('');
}
return recall;
}
module.exports={
login:function(req,res){
// function recall(data){
// res.write(data);
// res.end('');
// }
recall = getRecall(req,res);
optfile.readfile('./views/login.html',recall);
},
showimg:function(req,res){
res.writeHead(200,{'Content-Type':'image/jpeg'});
optfile.readImg('./imgs/scenery.png',res);
}
}
"./views/login.html"就是上面的login頁面
optfile.js:
var fs = require('fs');
var url = require('url');
module.exports={
readImg:function(path,res){
fs.readFile(path,'binary',function(err,file){ //binary指二進制流文件
if(err){
console.log(err);
}else{
res.write(file,'binary');
res.end();
}
});
console.log("異步方法執行完畢");
}
}