看了一段時間的Node.js就嘗試寫了一個小工具,設想是做一個自動的前端腳本部署工具,可實現的功能如下:1.同步最新的前端資源,2.創建服務器http/https,3.根據設定的規則部署文件。
目前只實現了創建一個靜態資源訪問服務器,1和3留待以後完善吧。
創建一個json格式的配置文件
js:javaScript文件存放的地址。css:樣式表存放的地址。
img:圖片資源存放的地址。
cType:http協議的conten-type值列表。
privatekey:https私鑰地址。
cert:https公鑰地址。
{
"js":"C:\\test\\frontendAutoDeploy\\static",
"css":"C:\\test\\frontendAutoDeploy\\static",
"img":"C:\\test\\frontendAutoDeploy\\static",
"cType":{
"js":"application/x-javascript",
"css":"text/css",
"jpg":"image/jpeg",
"png":"image/png"
},
"privatekey":"/ssl/privatekey.pem",
"cert":"/ssl/certificate.pem"
}
主要代碼
var http = require("http"),
https = require("https"),
fs = require("fs"),
path = require("path"),
conf = require("./lib/configuration.js");
options = {
key: fs.readFileSync(conf.privatekey),
cert: fs.readFileSync(conf.cert)
};
var app = function(req,res){
do{
//請求文件的後綴
var ext = (path.extname(req.url)).substring(1);
//請求文件content-type
var contentType = conf.cType[ext];
//請求的是否是圖片
if (ext==="ico"
||ext==="jpg"||ext==="png") {
ext = "img"
};
//請求文件路徑
var src ;
try{
src = path.join(conf[ext],req.url);
}catch(err){
console.log("msg:"+err.message+" "+conf[ext]+" url:"+req.url)
}
//設置http響應狀態和內容類型,輸出請求的文件。
if (fs.existsSync(src)) {
res.writeHead(200,{'Content-Type':contentType});
var stream = fs.createReadStream(src);
stream.on('data',function(chunk){
res.write(chunk);
});0.
stream.on('end',function(){
res.end();
});
}else{
res.writeHead(404,{'Content-Type':conf.cType[ext]});
res.end();
};
}while(false);
};
//創建http服務
http.createServer(app).listen(80);
//創建https服務
https.createServer(options,app).listen(443);
設置成命令行啓動
@node "C:\\test\\frontendAutoDeploy\index.js" %*
設置好之後,在cmd窗口中運行test命令,啓動腳本。openssl 證書的創建參考以下博文