Home  >  Article  >  Web Front-end  >  Node.js generates HttpStatusCode auxiliary class and publishes it to npm_Basic knowledge

Node.js generates HttpStatusCode auxiliary class and publishes it to npm_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:37:521528browse

As a good Restfull API, it not only depends on the semantics, readability, idempotence, and orthogonality of the service url, but also the http status code. A good Http Status Code gives the user a good response, such as 200 means normal success, 201 means creation success, 409 conflict, 404 resource does not exist, etc. So when I was making a demo based on node.js mongodb angularjs, I found that node.js express did not provide corresponding auxiliary classes, but I didn’t like to flood things like 201,404 with no language-level semantics everywhere, so I finally decided to write one myself. , but at the same time I am also very lazy and don’t like to do repetitive hard work. What should I do? Then copy it from the HttpStatusCode enumeration in C# that I am most familiar with. Finally, for simplicity on mac, I used node.js to parse msdn’s document about httpstatuscode to generate the node.js auxiliary class.

The code is very simple:

Copy code The code is as follows:

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

};




});

})();

The code is hosted on github: https://github.com/greengerong/node-httpstatuscode

The final generated class is:

Copy code The code is as follows:

View Code
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
};

Finally, considering that there may be many lazy people like me, I shared this code and published it to npm. You only need npm install httpstatuscode to make it simple and practical. The following is a test demo:

Copy code 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 people’s articles always have code with too much text. I hope the code can explain everything. Thank you for reading.

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