From 74c3b30f2f6c35eb6d4daeafad0464118dfbead5 Mon Sep 17 00:00:00 2001 From: coderaiser Date: Tue, 5 Feb 2013 09:16:16 -0500 Subject: [PATCH] refactored --- cloudcmd.js | 8 +-- lib/server.js | 109 +++++++++++++++++++++++++++++++++++-- lib/server/commander.js | 5 +- lib/server/main.js | 115 +++------------------------------------- lib/server/minify.js | 5 +- lib/server/rest.js | 5 +- 6 files changed, 126 insertions(+), 121 deletions(-) diff --git a/cloudcmd.js b/cloudcmd.js index 9ccbb2f6..5b250ca7 100644 --- a/cloudcmd.js +++ b/cloudcmd.js @@ -15,7 +15,7 @@ Util = main.util, update = main.update, - Server = main.require(LIBDIR + 'server'), + server = main.server, Minify = main.minify, Config = main.config, @@ -28,7 +28,7 @@ DIR = main.DIR; readConfig(); - Server.start(Config, { + server.start(Config, { appcache : appCacheProcessing, minimize : minimize, rest : rest, @@ -186,13 +186,13 @@ '-> auth'); pParams.name = main.HTMLDIR + lName + '.html'; - lRet = main.sendFile(pParams); + lRet = server.sendFile(pParams); }else if( Util.strCmp(lName, '/auth/github') ){ Util.log('* Routing' + '-> github'); pParams.name = main.HTMLDIR + lName + '.html'; - lRet = main.sendFile(pParams); + lRet = server.sendFile(pParams); }else if( Util.isContainStr(lName, CloudFunc.FS) || Util.isContainStr(lName, CloudFunc.NO_JS ) || Util.strCmp(lName, '/') || diff --git a/lib/server.js b/lib/server.js index 536ae120..eefea9ba 100644 --- a/lib/server.js +++ b/lib/server.js @@ -31,9 +31,15 @@ Socket = main.socket, http = main.http, + zlib = main.zlib, + fs = main.fs, Util = main.util, + ext = main.ext, - Server, Rest, Route, Minimize, Port, IP; + Server, Rest, Route, Minimize, Port, IP, + + OK = 200, + FILE_NOT_FOUND = 404; /* базовая инициализация */ function init(pAppCachProcessing){ @@ -58,7 +64,7 @@ * @param pConfig * @param pProcessing {index, appcache, rest} */ - exports.start = function start(pConfig, pProcessing) { + function start(pConfig, pProcessing) { if(!pProcessing) pProcessing = {}; @@ -105,7 +111,7 @@ } }else Util.log('Cloud Commander testing mode'); - } + }; /** @@ -162,7 +168,7 @@ function(pParams){ var lSendName = pParams && pParams.name || lName; - main.sendFile({ + sendFile({ name : lSendName, request : pReq, response : pRes @@ -177,4 +183,99 @@ } } + /** + * Функция создаёт заголовки файлов + * в зависимости от расширения файла + * перед отправкой их клиенту + * @param pName - имя файла + * @param pGzip - данные сжаты gzip'ом + */ + function generateHeaders(pName, pGzip, pQuery){ + var lRet, + lType = '', + lContentEncoding = '', + lCacheControl = 0, + + lExt = Util.getExtension(pName); + + if( Util.strCmp(lExt, '.appcache') ) + lCacheControl = 1; + + lType = ext[lExt] || 'text/plain'; + + if( !Util.isContainStr(lType, 'img') ) + lContentEncoding = '; charset=UTF-8'; + + if(Util.strCmp(pQuery, 'download') ) + lType = 'application/octet-stream'; + + + if(!lCacheControl) + lCacheControl = 31337 * 21; + + lRet = { + /* if type of file any, but img - + * then we shoud specify charset + */ + 'Content-Type': lType + lContentEncoding, + 'cache-control': 'max-age=' + lCacheControl, + 'last-modified': new Date().toString(), + /* https://developers.google.com/speed/docs/best-practices + /caching?hl=ru#LeverageProxyCaching */ + 'Vary': 'Accept-Encoding' + }; + + if(pGzip) + lRet['content-encoding'] = 'gzip'; + + return lRet; + } + + /** + * send file to client thru pipe + * and gzip it if client support + * + * @param pName - имя файла + * @param pGzip - данные сжаты gzip'ом + */ + function sendFile(pParams){ + var lRet, + lName, lReq, lRes; + + if(pParams){ + lName = pParams.name, + lReq = pParams.request, + lRes = pParams.response; + } + + if(lName && lRes && lReq){ + var lEnc = lReq.headers['accept-encoding'] || '', + lGzip = lEnc.match(/\bgzip\b/), + + lReadStream = fs.createReadStream(lName, { + 'bufferSize': 4 * 1024 + }); + + lReadStream.on('error', function(pError){ + lRes.writeHead(FILE_NOT_FOUND, 'OK'); + lRes.end(String(pError)); + }); + + lRes.writeHead(OK, generateHeaders(lName, lGzip) ); + + if (lGzip) + lReadStream = lReadStream.pipe( zlib.createGzip() ); + + lReadStream.pipe(lRes); + + lRet = true; + } + + return lRet; + } + + exports.generateHeaders = generateHeaders; + exports.sendFile = sendFile; + exports.start = start; + })(); diff --git a/lib/server/commander.js b/lib/server/commander.js index bb172372..316a2c0f 100644 --- a/lib/server/commander.js +++ b/lib/server/commander.js @@ -20,6 +20,7 @@ LIBDIR = main.LIBDIR, HTMLDIR = main.HTMLDIR, Util = main.util, + server = main.server, NOT_FOUND = 404, OK = 200, @@ -51,7 +52,7 @@ if(pStat.isDirectory()) fs.readdir(lPath, Util.call(readDir, pParams) ); else - main.sendFile({ + server.sendFile({ name : lPath, request : p.request, response : p.response @@ -400,7 +401,7 @@ lQuery = getQuery(p.request), /* download, json */ lGzip = isGZIP(p.request), - lHead = main.generateHeaders(lPath, lGzip, lQuery); + lHead = server.generateHeaders(lPath, lGzip, lQuery); /* если браузер поддерживает gzip-сжатие - сжимаем данные*/ Util.ifExec(!lGzip, diff --git a/lib/server/main.js b/lib/server/main.js index 451cb516..4142a734 100644 --- a/lib/server/main.js +++ b/lib/server/main.js @@ -13,18 +13,12 @@ SLASH, ISWIN32, - fs, - path, - zlib, - ext, - - OK = 200, - FILE_NOT_FOUND = 404; + path; /* Native Modules*/ exports.crypto = require('crypto'), exports.child_process = require('child_process'), - exports.fs = fs = require('fs'), + exports.fs = require('fs'), exports.http = require('http'), exports.https = require('https'), exports.path = path = require('path'), @@ -43,26 +37,23 @@ exports.JSONDIR = JSONDIR = DIR + 'json/', /* Functions */ - exports.generateHeaders = generateHeaders, - exports.sendFile = sendFile, - exports.require = mrequire, exports.librequire = librequire, exports.srvrequire = srvrequire, exports.rootrequire = rootrequire, /* compitability with old versions of node */ - exports.fs.exists = exports.fs.exists || exports.path.exists; + exports.fs.exists = exports.fs.exists || exports.path.exists; /* Needed Modules */ exports.util = Util = require(LIBDIR + 'util'), - exports.zlib = zlib = mrequire('zlib'), + exports.zlib = mrequire('zlib'), /* Main Information */ exports.config = jsonrequire('config'); exports.modules = jsonrequire('modules'); - exports.ext = ext = jsonrequire('ext'); + exports.ext = jsonrequire('ext'); exports.mainpackage = rootrequire('package'); @@ -77,15 +68,16 @@ exports.VOLUMES = getVolumes(), /* Additional Modules */ + exports.minify = srvrequire('minify').Minify; + exports.socket = srvrequire('socket'), + exports.server = librequire('server'), exports.auth = srvrequire('auth').auth, exports.appcache = srvrequire('appcache'), exports.cache = srvrequire('cache').Cache, exports.cloudfunc = librequire('cloudfunc'), exports.rest = srvrequire('rest').api, - exports.socket = srvrequire('socket'), exports.update = srvrequire('update'), exports.ischanged = srvrequire('ischanged'); - exports.minify = srvrequire('minify').Minify; exports.commander = srvrequire('commander'); /* * second initializing after all modules load, so global var is @@ -121,97 +113,6 @@ */ function isWin32(){ return process.platform === 'win32'; } - /** - * Функция создаёт заголовки файлов - * в зависимости от расширения файла - * перед отправкой их клиенту - * @param pName - имя файла - * @param pGzip - данные сжаты gzip'ом - */ - function generateHeaders(pName, pGzip, pQuery){ - var lRet, - lType = '', - lContentEncoding = '', - lCacheControl = 0, - - lExt = Util.getExtension(pName); - - if( Util.strCmp(lExt, '.appcache') ) - lCacheControl = 1; - - lType = ext[lExt] || 'text/plain'; - - if( !Util.isContainStr(lType, 'img') ) - lContentEncoding = '; charset=UTF-8'; - - if(Util.strCmp(pQuery, 'download') ) - lType = 'application/octet-stream'; - - - if(!lCacheControl) - lCacheControl = 31337 * 21; - - lRet = { - /* if type of file any, but img - - * then we shoud specify charset - */ - 'Content-Type': lType + lContentEncoding, - 'cache-control': 'max-age=' + lCacheControl, - 'last-modified': new Date().toString(), - /* https://developers.google.com/speed/docs/best-practices - /caching?hl=ru#LeverageProxyCaching */ - 'Vary': 'Accept-Encoding' - }; - - if(pGzip) - lRet['content-encoding'] = 'gzip'; - - return lRet; - } - - /** - * send file to client thru pipe - * and gzip it if client support - * - * @param pName - имя файла - * @param pGzip - данные сжаты gzip'ом - */ - function sendFile(pParams){ - var lRet, - lName, lReq, lRes; - - if(pParams){ - lName = pParams.name, - lReq = pParams.request, - lRes = pParams.response; - } - - if(lName && lRes && lReq){ - var lEnc = lReq.headers['accept-encoding'] || '', - lGzip = lEnc.match(/\bgzip\b/), - - lReadStream = fs.createReadStream(lName, { - 'bufferSize': 4 * 1024 - }); - - lReadStream.on('error', function(pError){ - lRes.writeHead(FILE_NOT_FOUND, 'OK'); - lRes.end(String(pError)); - }); - - lRes.writeHead(OK, generateHeaders(lName, lGzip) ); - - if (lGzip) - lReadStream = lReadStream.pipe( zlib.createGzip() ); - - lReadStream.pipe(lRes); - - lRet = true; - } - - return lRet; - } - /** * get volumes if win32 or get nothing if nix diff --git a/lib/server/minify.js b/lib/server/minify.js index 21969f07..7aeaff4c 100644 --- a/lib/server/minify.js +++ b/lib/server/minify.js @@ -19,7 +19,8 @@ LIBDIR = main.LIBDIR, HTMLDIR = main.HTMLDIR, Util = main.util, - Minify = main.require('minify'), + Minify = main.minify, + server = main.server, IsChanged = main.ischanged, COULD_NOT_MINIFY = 'Could not minify without minify module\n' + @@ -72,7 +73,7 @@ if(pChanged) Minify.optimize(pName, pParams); else - main.sendFile(pParams); + server.sendFile(pParams); }); } else{ diff --git a/lib/server/rest.js b/lib/server/rest.js index 6957bb31..d747c281 100644 --- a/lib/server/rest.js +++ b/lib/server/rest.js @@ -16,9 +16,10 @@ var main = global.cloudcmd.main, Util = main.util, Config = main.config, + server = main.server, APIURL = Config.api_url, OK = 200, - Header = main.generateHeaders('api.json', false); + Header = server.generateHeaders('api.json', false); /** * rest interface @@ -153,7 +154,7 @@ if( Util.isString(lFiles) ){ pParams.name = lFiles; - main.sendFile(pParams); + server.sendFile(pParams); lResult = null; }