Node.js生成HttpStatusCode輔助類發(fā)布到npm
作為一個(gè)好的Restfull Api不僅在于service url的語(yǔ)義,可讀性,冪等,正交,作為http狀態(tài)碼也很重要,一個(gè)好的Http Status Code給使用者一個(gè)很好的響應(yīng),比如200表示正常成功,201表示創(chuàng)建成功,409沖突,404資源不存在等等。所以在做一個(gè)基于node.js+mongodb+angularjs的demo時(shí)發(fā)現(xiàn)node.js express沒(méi)有提供相應(yīng)的輔助類,但是本人不喜歡將201,404這類毫無(wú)語(yǔ)言層次語(yǔ)義的東西到處充斥著,所以最后決定自己寫一個(gè),但是同時(shí)本人也很懶,不喜歡做重復(fù)的苦力活,怎么辦?那就從我最熟悉的c#中HttpStatusCode枚舉中copy出來(lái)吧,最后為了簡(jiǎn)便在mac上所以采用了利用node.js去解析msdn關(guān)于httpstatuscode的文檔生成node.js的輔助類。
代碼很簡(jiǎn)單:
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
最終生成類為:
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
};
最后考慮到或許還有很多像我一樣懶散的人,所以共享此代碼發(fā)布到了npm,只需要npm install httpstatuscode,便可以簡(jiǎn)單實(shí)用,如下是一個(gè)測(cè)試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");
懶人的文章總是代碼多余文字,希望代碼能說(shuō)明一切,感謝各位能閱讀。
相關(guān)文章
JavaScript刷新頁(yè)面的幾種方法總結(jié)
這篇文章主要介紹了JavaScript刷新頁(yè)面的幾種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03javascript 學(xué)習(xí)筆記(四) 倒計(jì)時(shí)程序代碼
javascript 學(xué)習(xí)筆記(四) 倒計(jì)時(shí)程序代碼,需要的朋友可以參考下。2011-04-04Javascript基礎(chǔ)教程之關(guān)鍵字和保留字匯總
這篇文章主要介紹了Javascript基礎(chǔ)教程之關(guān)鍵字和保留字匯總,需要的朋友可以參考下2015-01-01JavaScript 學(xué)習(xí)筆記之基礎(chǔ)中的基礎(chǔ)
這篇文章主要介紹了JavaScript 學(xué)習(xí)筆記系列的第一篇文章,跟所有開(kāi)篇一樣,本文我們介紹的都是些基礎(chǔ)中的基礎(chǔ)知識(shí),雖然都是基礎(chǔ),但建議大家不要略過(guò)此文2015-01-01網(wǎng)頁(yè)收藏夾顯示ICO圖標(biāo)(代碼少)
在添加網(wǎng)頁(yè)到收藏夾之后會(huì)看到一個(gè)漂亮的圖標(biāo),很好奇是怎么實(shí)現(xiàn)的呢?下面小編就給大家講解下網(wǎng)頁(yè)收藏夾顯示ICO圖標(biāo)(代碼少),有需要的小伙伴可以來(lái)參考下2015-08-08javascript、php關(guān)鍵字搜索函數(shù)的使用方法
這篇文章主要介紹了javascript、php關(guān)鍵字搜索函數(shù)的使用方法的相關(guān)資料,需要的朋友可以參考下2018-05-05javascript 全等號(hào)運(yùn)算符使用說(shuō)明
看到這樣一行代碼 if(typeof item === "string" ) ,看見(jiàn)有3個(gè)等號(hào)以前從沒(méi)這么寫過(guò),可能是我的JS技術(shù)還處于初級(jí)的原因吧,我去網(wǎng)上查了一些資料網(wǎng)上說(shuō)這是全等于符號(hào)2010-05-05