node.js对于追逐全栈开发的小伙伴们自然不陌生。他是建立与chrome v8引擎下的高性能,异步io、事件驱动javascript语言,使编写高性能web服务轻而易举。今天要分享的是一个使用node.js逐步推演建立一个完善的json服务的过程。通过对代码逐步完善来介绍node.js的特点及执行流程。闲话少许,进入正题。
业务场景描述:监听指定端口,分析请求url,返回对应的图片目录或图片文件列表。
round 1:搭建json服务 监听8000端口
var _http=require(http);
var _url=require(url);
var _fs=require(fs);
/**
* test res show message is success!
*/
var _server=_http.createserver((req,res)=>{
console.log(json webservice is running\n);
res.end(hello accp!);
});
_server.listen(8000);
已上代码实现监听本地8000端口,当通过浏览器访问时,即可触发对应代码。如图
round 2 : 返回json格式数据
var _http=require(http);
var _url=require(url);
var _fs=require(fs);
/**
* test res show json message is success!
*/
var _server=_http.createserver((req,res)=>{
console.log(json sebservice is running!\n);
//http://nodejs.cn/api/http.html#http_response_writehead_statuscode_statusmessage_headers
//response html head http://www.runoob.com/http/http-header-fields.html
//content-type mime values
//a pplication/msword doc microsoft word
// application/octet-stream bin dms lha lzh exe class 可执行程序
// application/pdf pdf adobe acrobat
// application/postscript ai eps ps postscript
// appication/powerpoint ppt microsoft powerpoint
// appication/rtf rtf rtf 格式
// appication/x-compress z unix 压缩文件
// application/x-gzip gz gzip
// application/x-gtar gtar tar 文档 (gnu 格式 )
// application/x-shockwave-flash swf macromedia flash
// application/x-tar tar tar(4.3bsd)
// application/zip zip winzip
// audio/basic au snd sun/next 声音文件
// audio/mpeg mpeg mp2 mpeg 声音文件
// audio/x-aiff mid midi rmf midi 格式
// audio/x-pn-realaudio ram ra real audio 声音
// audio/x-pn-realaudio-plugin rpm real audio 插件
// audio/x-wav wav microsoft windows 声音
// image/cgm cgm 计算机图形元文件
// image/gif gif compuserve gif 图像
// image/jpeg jpeg jpg jpe jpeg 图像
// image/png png png 图像
// text/html html
// text/plain txt
// text/xml xml
// text/json json字符串
res.writehead(200,{'content-type':'text/json'});
var out={
err:null,
data:{
showmessage:hello world
}
};
res.end(json.stringify(out));
});
_server.listen(8000);
round 3:测试 json webservice 输出 文件夹列表 列表
/**
*
* @authors your name (you@example.org)
* @date 2018-02-21 14:44:34
* @version $id$
*/
var _http=require(http);
var _url=require(url);
var _fs=require(fs);
/**
* 测试 json webservice 输出 文件夹列表
*/
var _server=_http.createserver((req,res)=>{
console.log(json webservice is running!\n);
var out={};
load_image_list((err,files)=>{
if(err){
res.writehead(403,{
content-type:text/json; charset=utf-8
});
out={err:err,data:{}};
res.end(json.stringify(out));
return;
}
//指定 返回字符串编码
res.writehead(200,{
content-type:text/json; charset=utf-8
});
out={err:err,data:{imagelist:files}};
res.end(json.stringify(out),'utf-8');
return;
});
//http://nodejs.cn/api/fs.html#fs_fs_readdir_path_options_callback
});
/**
* 初始化 图片列表 返回 指定图片文件夹列表
* bug 未对目录下 文件类型进行判断 同时返回 当前目录下 所有文件类型
* @param {function} callback 回调函数
*
* @return {[type]} [description]
*/
var load_image_list=function(callback){
_fs.readdir(images/,(err,files)=>{
if(err){
callback(err);
console.log(load_image_list try exception!\n);
return;
}
callback(null,files);
});
};
_server.listen(8000);
这里可以看到load_image_list方法注释内容提到,当前代码存在一定的漏洞,如果当前文件夹目录下存在图片文件,在返回结果时也会返回如图。针对此bug修改load_image_list。
**
* 初始化 图片列表 返回 指定图片文件夹列表
* 增加 对指定目录下 文件类型的判断 只返回 文件夹
* @param {function} callback 回调函数
*
* @return {[type]} [description]
*/
var load_image_list=function(callback){
_fs.readdir('images/',(err,files)=>{
if(err){
console.log(load image list throw exception!\n);
callback(err);
return;
}
var only_dir=[];
//创建 匿名方法 通过递归方式 将异步判断 变更为 同步判断
(function rtnpathisdirlist(index){
if(index==files.length){
callback(null,only_dir);
return;
}
_fs.stat(images/+files[index], (err,stats)=>{
if(err){
console.log(load image list check file type throw exception!\n);
callback(err);
return;
}
if(stats.isdirectory()){
only_dir.push(files[index]);
}
rtnpathisdirlist(index+1);
return;
});
})(0);
});
};
round 4 :增加 路由器 功能 针对 传递进来的 url进行 分析
/**
*
* @authors your name (you@example.org)
* @date 2018-02-21 15:01:25
* @version $id$
*/
var _http=require(http);
var _url=require(url);
var _fs=require(fs);
/**
* 测试 json webservice 输出 文件夹列表
* 增加 路由器 功能 针对 传递进来的 url进行 分析
* 增加 加载 图片列表 文件目录 输入
*/
var _url=require('url');
var _server=_http.createserver((req,res)=>{
console.log(json webservice is running!\n);
var out={};
//增加 请求 url 的分析
console.log(req.url);
var urlvalue=req.url;
var urllength=urlvalue.length;
//console.log(urlvalue.substr(1,11)+urlvalue.substr(1,11));
//排除 浏览器 发起的 获取 图标请求
if(urlvalue==/favicon.ico){
console.log(web brower favicon request!\n);
res.end();
return;
}
if(urlvalue==/images.json){
//获取 根目录 文件夹列表
console.log(load images list is running!\n);
handle_list_image(req,res,urlvalue.substr(1,6)+/);
return;
}else if(urlvalue.substr(1,6)==images&&urlvalue.substr(urllength-4)==json){
//加载 某一个 目录下 的文件
console.log(load image path:+urlvalue.substr(1,urlvalue.length-6));
handle_list_imagefile(req,res,urlvalue.substr(1,urlvalue.length-6)+/);
return;
}else{
//无正常 数据 加载 返回404 错误。
sendfailmessage(404,请求页面不存在,res);
console.log(error);
return;
}
//http://nodejs.cn/api/fs.html#fs_fs_readdir_path_options_callback
});
/**
* 获取图片列表
* 增加加载图片列表路径参数
* 将返回成功信息和失败信息进行封装
*
* @param {[type]} req [description]
* @param {[type]} res [description]
* @param {[string]} filepath [加载更目录]
*
* @return {[type]} [description]
*/
var handle_list_image=function(req,res,filepath){
load_image_list(filepath,(err,files)=>{
if(err){
// res.writehead(403,{
// content-type:text/json; charset=utf-8
// });
// out={err:err,data:{}};
// res.end(json.stringify(out));
sendfailmessage(403,err,res);
return;
}
//指定 返回字符串编码
// res.writehead(200,{
// content-type:text/json; charset=utf-8
// });
// out={err:null,data:{imagelist:files}};
// res.end(json.stringify(out),'utf-8');
//
var data={imagelist:files};
sendsuccessmessage(data,res);
return;
});
};
/**
* 获取文件 图片文件列表
*
* @param {[type]} req [description]
* @param {[type]} res [description]
* @param {[type]} filepath [description]
*
* @return {[type]} [description]
*/
var handle_list_imagefile=function(req,res,filepath){
load_imagefile_list(filepath,(err,files)=>{
if(err){
// res.writehead(403,{
// content-type:text/json; charset=utf-8
// });
// out={err:err,data:{}};
// res.end(json.stringify(out));
sendfailmessage(403,err,res);
return;
}
//指定 返回字符串编码
// res.writehead(200,{
// content-type:text/json; charset=utf-8
// });
// out={err:null,data:{imagelist:files}};
// res.end(json.stringify(out),'utf-8');
//
var data={imagelist:files};
sendsuccessmessage(data,res);
return;
});
};
/**
* 返回成功信息
*
* @param {json} datacontent 返回数据json信息
* @param {response} res [description]
*
* @return {[type]} [description]
*/
var sendsuccessmessage=function(datacontent,res){
//指定 返回字符串编码
res.writehead(200,{
content-type:text/json; charset=utf-8
});
out={err:null,data:datacontent};
res.end(json.stringify(out),'utf-8');
}
/**
* 返回失败信息
*
* @param {int} code 失败代码
* @param {error} err [description]
* @param {[type]} res [description]
*
* @return {[type]} [description]
*/
var sendfailmessage=function(code,err,res){
res.writehead(code,{
content-type:text/json; charset=utf-8
});
out={err:err,data:{}};
res.end(json.stringify(out));
}
/**
* 初始化 图片列表 返回 指定图片文件夹列表
* 增加 对指定目录下 文件类型的判断 只返回 文件夹
* 增加 遍历目录 变量
* @param {stinrg} filepath 加载目录
* @param {function} callback 回调函数
*
* @return {[type]} [description]
*/
var load_image_list=function(filepath,callback){
_fs.readdir(filepath,(err,files)=>{
if(err){
console.log(load image list throw exception!\n);
callback(err);
return;
}
var only_dir=[];
//创建 匿名方法 通过递归方式 将异步判断 变更为 同步判断
(function rtnpathisdirlist(index){
if(index==files.length){
callback(null,only_dir);
return;
}
_fs.stat(filepath+files[index], (err,stats)=>{
if(err){
console.log(load image list check file type throw exception!\n);
callback(err);
return;
}
if(stats.isdirectory()){
only_dir.push(files[index]);
}
rtnpathisdirlist(index+1);
return;
});
})(0);
});
};
/**
* 初始化 图片列表 返回 指定图片文件列表
* 增加 对指定目录下 文件类型的判断 只返回 文件
* 增加 遍历目录 变量
* @param {stinrg} filepath 加载目录
* @param {function} callback 回调函数
*
* @return {[type]} [description]
*/
var load_imagefile_list=function(filepath,callback){
_fs.readdir(filepath,(err,files)=>{
if(err){
console.log(load image file list throw exception!\n);
callback(err);
return;
}
var only_dir=[];
//创建 匿名方法 通过递归方式 将异步判断 变更为 同步判断
(function rtnpathisdirlist(index){
if(index==files.length){
callback(null,only_dir);
return;
}
_fs.stat(filepath+files[index], (err,stats)=>{
if(err){
console.log(load image list check file type throw exception!\n);
callback(err);
return;
}
if(stats.isfile()&&files[index].substr(files[index].length-3,3)==jpg){
console.log(files[index]:+files[index]);
console.log(files[index].substr(files[index].length-3,3):+files[index].substr(files[index].length-3,3)+\n);
only_dir.push(files[index]);
}
rtnpathisdirlist(index+1);
return;
});
})(0);
});
};
_server.listen(8000);
这里主要是增加了路由的功能,测试访问路径如下:
http://localhost:8000 返回结果如图;
http://localhost:8000/images.json 返回结果如图;
http://localhost:8000/images/image1.json 返回结果如图;
相关推荐:
js调用json的方法总结
html里table表数据如何转为json格式
ajax前后端使用json进行交互实现方法
以上就是node.js搭建简易版json服务的详细内容。
