Usually we develop projects should be used when the picture, then the picture nodejs how to read it?
We look at, because the number of pages in a picture is uncertain, but we can not write each image to its src path, this time the best way is to write a special read picture route by route load picture, so quick and easy our understanding.
File Directory:
I want to load images in index page
Note: Question mark? Represents the front part of the route, the path is a question mark behind the picture (relative to the server file), I was first_server.js file
1, in their definition of the new directory server files
I was:
first_server.js
var http=require('http');
var url=require('url');
var router=require('./module/router');
http.createServer(function (request,response) {
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
if (request.url!=='/favicon.ico'){//清除二次访问
var path=url.parse(request.url).pathname;//获取当前路径
if(path==='/')path='/index';
path=path.substr(1);//获取去掉根符号‘/’的当前路径
router[path](request,response);//路由,path是一个变量,如login、register、index
}
}).listen(5200);//端口号为5200
Explanation : The value is not the same path twice,
if (path === '/') action path = '/ index' if the time of the visit is not input path, to enter the index page
Note : router [path] must be defined through the routing module inside job, otherwise there will not be found error
2, write routing module (router.js)
var url = require('url');
var optfile=require('./optfile');//导入自定义模块要加路径'./'
module.exports={
readImg:function(req,res){
optfile.readImg(req,res);
},
index:function(req,res){
optfile.index('./file/index.html',res);
}
}
3, the preparation of operating documents (optfile.js)
var fs = require('fs');
function recall(res,data,ext){
if (!ext)ext='html';//默认输出格式为HTML
res.writeHead(200, {'Content-Type': 'text/'+ext+';charset=utf-8'});
res.end(data);//向浏览器输出取得的数据
}
module.exports={
readImg:function (req,res) {
var path=req.url.split('?')[1];
var data = fs.readFile(path,'binary',function (err,data) {
if (!err){
res.writeHead(200, {'Content-Type': 'image/jpeg'});//输出类型
res.write(data,'binary');//二进制方式
}else {
res.end('err');
}
})
},
index:function (path,res) {
var data = fs.readFile(path,function (err,data) {
if (!err){
data=data.toString();
recall(res,data);
}else {
res.end('err');
}
})
}
};
Because the picture is transmitted in binary form in nodejs, so the output file to add 'binnary' represent a binary output.
Req.url equivalent request.url represents achievement of the path of the current request, here to represent all the image path,
req.url .split ( '?') represents the path will be made of string? Split into an array,
req.url.split ( '?') [. 1] represented by taking a string? No later parts, namely the relative path pictures
do not understand can see below, I console it:
operation result:
Reproduced in: https: //www.jianshu.com/p/cfeb8c082651