Home  >  Article  >  Web Front-end  >  Node.JS builds a simple version of json service

Node.JS builds a simple version of json service

小云云
小云云Original
2018-02-23 13:12:562025browse

Node.JS is naturally no stranger to friends who are pursuing full-stack development. It is built with the high-performance, asynchronous IO, event-driven JavaScript language under the chrome V8 engine, making writing high-performance web services a breeze. What I want to share today is a step-by-step process of building a complete json service using Node.JS. By gradually improving the code, we will introduce the characteristics and execution process of Node.JS. Enough chatter, let’s get to the point.

业务场景描述:监听指定端口,分析请求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);

The code has been uploaded to monitor the local 8000 port. When accessed through the browser, the corresponding code can be triggered. As shown in the picture

Node.JS builds a simple version of json service##

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);

Node.JS builds a simple version of json service

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);

Node.JS builds a simple version of json service
Here you can see that the comment content of the load_image_list method mentions that there are certain loopholes in the current code. If there are image files in the current folder directory, the picture will also be returned when the result is returned. Modify load_image_list for this bug.
Node.JS builds a simple version of json service

**
 * 初始化 图片列表 返回 指定图片文件夹列表
 * 增加 对指定目录下 文件类型的判断 只返回 文件夹
 * @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);

The main purpose here is to add the routing function. The test access path is as follows: http://localhost :8000 The returned result is as shown in the figure;

Node.JS builds a simple version of json service

http://localhost:8000/images.json The returned result is as shown in the figure;


Node.JS builds a simple version of json service

http://localhost:8000/images/image1.json The return result is as shown in the figure;


Node.JS builds a simple version of json service

Related recommendations:


Summary of how js calls json

How to convert table data in html to Json format

Ajax front-end and back-end interaction implementation method using JSON

The above is the detailed content of Node.JS builds a simple version of json service. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn