Node.js 练习一

看了一段时间的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);


设置成命令行启动

假设启动脚本是“C:\\test\\frontendAutoDeploy\index.js”,1.把路径“C:\\test\\frontendAutoDeploy\”放到PATH环境变量中,2在当前路径下创建test.cmd文件,文件内容
@node "C:\\test\\frontendAutoDeploy\index.js" %*
设置好之后,在cmd窗口中运行test命令,启动脚本。

openssl 证书的创建参考以下博文

借鉴博文一  借鉴博文二 

你可能感兴趣的:(Node.js 练习一)