nj_readImg.jsjavascript
var http = require('http');
var optfile = require('./model/openfile');
http.createServer(function (request, response) {
//response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
response.writeHead(200, {'Content-Type':'image/jpeg'}); //這裏的類型是image/jpeg
if(request.url!=="/favicon.ico"){ //清除第2此訪問
console.log('訪問');
//response.write('hello,world');//不能向客戶端輸出任何字節
optfile.readImg('./imgs/1.jpg',response);
//------------------------------------------------
console.log("繼續執行");
//response.end('hell,世界');//end在方法中寫過
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
openfile.jshtml
var fs= require('fs');//node自帶的類 module.exports={ readImg:function(path,res){ fs.readFile(path,'binary',function(err, file) {//主要這裏的‘binary’ if (err) { console.log(err); return; }else{ console.log("輸出文件"); //res.writeHead(200, {'Content-Type':'image/jpeg'}); res.write(file,'binary');//這裏輸出的是一個二進制的文件流 res.end(); } }); } }
這裏網站請求http://localhost:8000/readFile 就能夠讀出圖片java
可是這個代碼裏面只能讀二進制,不能寫任何的字符串,不然會報錯的node
------------------------------------------------------------------------------------------------閉包
當咱們須要加載一個html中有文字和圖片的時候就須要改造一下路由器的請求方式異步
nj_html.js函數
var http = require('http'); var url = require('url'); var router = require('./model/router'); http.createServer(function (request, response) { if(request.url!=="/favicon.ico"){ var pathname = url.parse(request.url).pathname;//獲取路徑名稱 pathname = pathname.replace(/\//,""); //正則去掉/ router[pathname](request,response);//根據路徑名稱獲取到函數從而調用函數 } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/');
roter.js 中寫一個閉包方法網站
var openfile = require('./openfile'); function getRecall(req,res){ res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); function recall(data){ res.write(data); res.end('');//不寫則沒有http協議尾 } return recall; } module.exports={ login:function(req,res){ recall = getRecall(req,res);//單獨寫一個閉包方法 openfile.readfile('./view/login.html',recall); }, zhuce:function(req,res){ recall = getRecall(req,res); openfile.readfile('./view/zhuce.html',recall); }, showimg:function(path,res){ res.writeHead(200,{'Content-Type':'image/jpeg'}); //圖片加載的請求頭 openfile.readImg('./imgs/1.jpg',res); } }
openfile.jsui
var fs= require('fs');//node自帶的類 module.exports={ readfile:function(path,recall){ //異步執行 fs.readFile(path, function (err, data) { if (err) { console.log(err); }else{ console.log(data.toString()); recall(data); } }); }, readImg:function(path,res){//圖片加載的方法 fs.readFile(path,'binary',function(err, file) { if (err) { console.log(err); return; }else{ console.log("輸出文件"); //res.writeHead(200, {'Content-Type':'image/jpeg'}); res.write(file,'binary'); res.end(); } }); } }
login.htmlurl
<!DOCTYPE html> <html> <head> <title></title> </head> <body> 登入頁面 <img src="./showimg"> </body> </html>
網頁請求http://localhost:8000/login
程序會先加載login.html 當加載到img的時候會再次請求showimg的方法在加載圖片