问题:在手机或一些常用网站上,宽度自适应是很难写的一部分内容,基于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 + ".");