Node. js generates the HttpStatusCode helper class and publishes it to npm _ basic knowledge

Source: Internet
Author: User
This article introduces the use of Node. js is Node. js generates the HttpStatusCode helper class and releases it to npm. If you need it, you can refer to it. As a good Restfull Api, not only does it lie in the semantics, readability, power, and orthogonal of service URLs, as an http Status Code, it is also very important. A good Http Status Code provides a good response to the user. For example, 200 indicates normal success, 201 indicates successful creation, 409 conflict, and 404 indicates that the resource does not exist. Therefore, we are working on a node-based architecture. node is found in js + mongodb + angularjs demo. js express does not provide the corresponding auxiliary classes, but I do not like to fill the 201,404 class of things without hierarchical semantics everywhere, so I finally decided to write it myself, but I am also very lazy, what should I do if I do not like repeated hard work? Copy the code from the HttpStatusCode enumeration in c #, which I am most familiar with. In the end, node is used for mac convenience. js parses msdn documentation on httpstatuscode to generate node. js helper class.

The code is simple:

The Code is as follows:


Var http = require ('http ');

Var fs = require ('fs ');

Var $ = require ('jquery ');

Var output = "httpStatusCode/index. js? 6.1.3 ";

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

};




});

})();

Code boarding at github: https://github.com/greengerong/node-httpstatuscode

The final generation class is:

The Code is as follows:


View Code
Exports. httpStatusCode = {
"Continue": 100,
"SwitchingProtocols": 101,
"OK": 200,
"Created": 201,
"Accepted": 202,
"Nonauthoritativeinfo": 203,
"NoContent": 204,
"ResetContent": 205,
"PartialContent": 206,
& Quot; MultipleChoices & quot;: 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
};

Finally, considering that there may be a lot of people who are as lazy as I do, sharing this code to npm can be simple and practical. Here is a test demo:

The Code is as follows:


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

Lazy articles are always redundant texts in the code. I hope the code can describe everything. Thank you for reading this article.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.