利用Node.js为Node.js生成HttpStatusCode辅助类并发布到npm

简介:

      作为一个好的Restfull Api不仅在于service url的语义,可读性,幂等,正交,作为http状态码也很重要,一个好的Http Status Code给使用者一个很好的响应,比如200表示正常成功,201表示创建成功,409冲突,404资源不存在等等。所以在做一个基于node.js+mongodb+angularjs的demo时发现node.js express没有提供相应的辅助类,但是本人不喜欢将201,404这类毫无语言层次语义的东西到处充斥着,所以最后决定自己写一个,但是同时本人也很懒,不喜欢做重复的苦力活,怎么办?那就从我最熟悉的c#中HttpStatusCode枚举中copy出来吧,最后为了简便在mac上所以采用了利用node.js去解析msdn关于httpstatuscode的文档生成node.js的辅助类。

    代码很简单:

 

var http = require('http');

var fs = require('fs');

var $ = require('jquery');

var output = "httpStatusCode/index.js";

(function(){

   

    String.format = function() {

        var s = arguments[0];

        for (var i = 0; i < arguments.length - 1; i++) {

            var reg = new RegExp("\\{" + i + "\\}", "gm");

            s = s.replace(reg, arguments[i + 1]);

        }


 

        return s;

    };


 

    var options = {

        host:'msdn.microsoft.com',

        port:80,

        path:'/zh-cn/library/system.net.httpstatuscode.aspx'

    };


 

    http.get(options,function (response) {

        var html = "";

        response.on("data",function (chunk) {

            html += chunk;

        }).on("end", function () {

            handler(html);

        }).on('error', function (e) {

            console.log("Got error: " + e.message);

        });


 

    function getHttpStatusCode(htmlString) {

        var $doc = $(html);

        var rows = $doc.find("table#memberList tr:gt(0)");

        var status = {};

        rows.each(function(i,row){

            status[$(row).find("td:eq(1)").text()] =

                parseInt($(row).find("td:eq(2)").text().match(/\d+/).toString());

        });

       return status;

    };

    

    function generateCode(status){

       var code = "";

       code += "exports.httpStatusCode = " + JSON.stringify(status) + ";";

       return code;

    };

   

    function writeFile(code){

        fs.writeFile(output, code, function(err) {

            if(err) {

                console.log(err);

            } else {

                console.log("The file was saved " + output + "!");

            }

        });

    };


 

    function handler(html){

       var status = getHttpStatusCode(html);

       var code = generateCode(status);

       writeFile(code);

    };


 

  });

})();

代码寄宿在github:https://github.com/greengerong/node-httpstatuscode

最终生成类为:

exports.httpStatusCode = { 
    "Continue": 100, 
    "SwitchingProtocols": 101, 
    "OK": 200, 
    "Created": 201, 
    "Accepted": 202, 
    "NonAuthoritativeInformation": 203, 
    "NoContent": 204, 
    "ResetContent": 205, 
    "PartialContent": 206, 
    "MultipleChoices": 300, 
    "Ambiguous": 300, 
    "MovedPermanently": 301, 
    "Moved": 301, 
    "Found": 302, 
    "Redirect": 302, 
    "SeeOther": 303, 
    "RedirectMethod": 303, 
    "NotModified": 304, 
    "UseProxy": 305, 
    "Unused": 306, 
    "TemporaryRedirect": 307, 
    "RedirectKeepVerb": 307, 
    "BadRequest": 400, 
    "Unauthorized": 401, 
    "PaymentRequired": 402, 
    "Forbidden": 403, 
    "NotFound": 404, 
    "MethodNotAllowed": 405, 
    "NotAcceptable": 406, 
    "ProxyAuthenticationRequired": 407, 
    "RequestTimeout": 408, 
    "Conflict": 409, 
    "Gone": 410, 
    "LengthRequired": 411, 
    "PreconditionFailed": 412, 
    "RequestEntityTooLarge": 413, 
    "RequestUriTooLong": 414, 
    "UnsupportedMediaType": 415, 
    "RequestedRangeNotSatisfiable": 416, 
    "ExpectationFailed": 417, 
    "UpgradeRequired": 426, 
    "InternalServerError": 500, 
    "NotImplemented": 501, 
    "BadGateway": 502, 
    "ServiceUnavailable": 503, 
    "GatewayTimeout": 504, 
    "HttpVersionNotSupported": 505 
};

 

最后考虑到或许还有很多像我一样懒散的人,所以共享此代码发布到了npm,只需要npm install httpstatuscode,便可以简单实用,如下是一个测试demo:

 

var httpStatusCode = require("httpstatuscode").httpStatusCode;


 

var toBeEqual = function (actual,expected){

    if(actual !== expected){

     throw (actual + " not equal " + expected);

    }

};


 

toBeEqual(httpStatusCode.OK,200);

toBeEqual(httpStatusCode.Created,201);

toBeEqual(httpStatusCode.BadRequest,400);

toBeEqual(httpStatusCode.InternalServerError,500);


 

console.log(httpStatusCode);

console.log("success");

懒人的文章总是代码多余文字,我喜欢代码说明一切,感谢各位能阅读此随笔。





 本文转自 破狼 51CTO博客,原文链接:http://blog.51cto.com/whitewolfblog/1174284,如需转载请自行联系原作者


相关文章
|
8月前
|
JavaScript 前端开发 安全
【逆向】Python 调用 JS 代码实战:使用 pyexecjs 与 Node.js 无缝衔接
本文介绍了如何使用 Python 的轻量级库 `pyexecjs` 调用 JavaScript 代码,并结合 Node.js 实现完整的执行流程。内容涵盖环境搭建、基本使用、常见问题解决方案及爬虫逆向分析中的实战技巧,帮助开发者在 Python 中高效处理 JS 逻辑。
|
Web App开发 JavaScript 前端开发
Node.js 是一种基于 Chrome V8 引擎的后端开发技术,以其高效、灵活著称。本文将介绍 Node.js 的基础概念
Node.js 是一种基于 Chrome V8 引擎的后端开发技术,以其高效、灵活著称。本文将介绍 Node.js 的基础概念,包括事件驱动、单线程模型和模块系统;探讨其安装配置、核心模块使用、实战应用如搭建 Web 服务器、文件操作及实时通信;分析项目结构与开发流程,讨论其优势与挑战,并通过案例展示 Node.js 在实际项目中的应用,旨在帮助开发者更好地掌握这一强大工具。
565 1
|
存储 JavaScript 前端开发
在NodeJS中使用npm包进行JS代码的混淆加密
总的来说,使用“javascript-obfuscator”包可以帮助我们在Node.js中轻松地混淆JavaScript代码。通过合理的配置,我们可以使混淆后的代码更难以理解,从而提高代码的保密性。
1227 9
|
JavaScript
node环境之Error: Cannot find module ‘chalk’ 报错无法解决的问题—-网上说让你npm install chalk 基本是没有用的-优雅草央千澈解决方案
node环境之Error: Cannot find module ‘chalk’ 报错无法解决的问题—-网上说让你npm install chalk 基本是没有用的-优雅草央千澈解决方案
1172 13
node环境之Error: Cannot find module ‘chalk’ 报错无法解决的问题—-网上说让你npm install chalk 基本是没有用的-优雅草央千澈解决方案
node环境之当我们遇到需要付费的依赖库@fortawesome/fontawesome-pro导致npm install无法进行怎么办-fontawesome-pro依赖库
node环境之当我们遇到需要付费的依赖库@fortawesome/fontawesome-pro导致npm install无法进行怎么办-fontawesome-pro依赖库
475 3
node环境之当我们遇到需要付费的依赖库@fortawesome/fontawesome-pro导致npm install无法进行怎么办-fontawesome-pro依赖库
|
存储 资源调度 JavaScript
npm、cnpm 和 pnpm 是三种常用的 Node.js 包管理工具
npm、cnpm 和 pnpm 是三种常用的 Node.js 包管理工具。npm 是官方默认的包管理器,提供依赖管理、安装和更新等功能;cnpm 是由阿里巴巴开发的 npm 镜像,专为中国大陆用户优化,解决下载速度慢的问题;pnpm 通过硬链接技术提高安装速度并节省磁盘空间,特别适合磁盘资源紧张的环境。三者命令类似,但各有特色,开发者可根据需求选择合适的工具。
2106 5
|
存储 JavaScript NoSQL
Node.js新作《循序渐进Node.js企业级开发实践》简介
《循序渐进Node.js企业级开发实践》由清华大学出版社出版,基于Node.js 22.3.0编写,包含26个实战案例和43个上机练习,旨在帮助读者从基础到进阶全面掌握Node.js技术,适用于初学者、进阶开发者及全栈工程师。
323 9
|
开发框架 JavaScript 前端开发
Node.js日记:客户端和服务端介绍、Node.js介绍
Node.js日记:客户端和服务端介绍、Node.js介绍
|
JavaScript 前端开发 开发者
JavaScript 类继承
JavaScript 类继承
157 1
|
JavaScript 前端开发
JavaScript 中,可以使用类继承来创建子类
JavaScript 中,可以使用类继承来创建子类
168 0