基于Nodejs+Less的动态CSS

问题:在手机或一些常用网站上,宽度自适应是很难写的一部分内容,基于Less的变量会变更的更好;

            但穷举各种情况比较困难,所以,采用变量名来获取会更好


工具:NodeJS+Less


请求地址如:

http://localhost:3000/test_300.less

基于安全考虑:请限制生成范围,以下未考虑文件部署等问题,可进行修改从来适用


示例代码:

var PORT = 3000;

var http = require('http');
var url=require('url');
var fs=require('fs');
var path=require('path');
var exec = require('child_process').exec;  

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("assets", pathname);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
	var tmpPath = realPath.replace(/\.less$/g,".css");
	if(ext==='less'&&!fs.existsSync(tmpPath)){
		compile_less(realPath,tmpPath,function(){
			resp(tmpPath,response);
		});
	}else{
		realPath = ext==='less'?realPath.replace(/\.less$/g,".css"):realPath;
		resp(realPath,response);
	}
});

function resp(realPath,response){
	fs.exists(realPath, function (exists) {
		if (!exists) {
			response.writeHead(404, {
				'Content-Type': 'text/plain'
			});

			response.write("This request URL  was not found on this server.");
			response.end();
		} else {
			fs.readFile(realPath, "binary", function (err, file) {
				if (err) {
					response.writeHead(500, {
						'Content-Type': 'text/plain'
					});
					response.end(err);
				} else {
					var contentType = "text/css";
					response.writeHead(200, {
						'Content-Type': contentType
					});
					response.write(file, "binary");
					response.end();
				}
			});
		}
	});
}
var globalVarReg = new RegExp("(\\d+)\\.less$");
function compile_less(input_file, output_file, callback) {
	var v = globalVarReg.exec(input_file);
	if(v!=null){
		input_file = input_file.replace(/_\d+\.less$/g,".less");
		var cmd = ['lessc ', '-global-var="bodyWidth=',v[1],'px" ',input_file, ' > ', output_file].join('');  
	}else{
		var cmd = ['lessc ', input_file, ' > ', output_file].join('');  
	}
    exec(cmd, {encoding: 'utf-8'},   
	function(error, stdout, stderr) {  
		if(error !== null) {  
			console.log(error);  
			return;  
		}   
		callback();
	});  
}  
  
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值