From 3104ee167c96e73fdddd1bdea75282832dcb934a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8A=A0=E9=87=8C?= Date: Tue, 21 Oct 2014 13:44:22 +0800 Subject: [PATCH] update local rule --- rule_sample/rule_use_local_data.js | 50 +++++++----------------------- 1 file changed, 11 insertions(+), 39 deletions(-) diff --git a/rule_sample/rule_use_local_data.js b/rule_sample/rule_use_local_data.js index a9221c8..507b78e 100644 --- a/rule_sample/rule_use_local_data.js +++ b/rule_sample/rule_use_local_data.js @@ -1,53 +1,25 @@ //replace all the images with local one - -var url = require("url"), +var url = require("url"), path = require("path"), - fs = require("fs"), - buffer = require("buffer"); + fs = require("fs"); -var map = [ - { - "host" :/./, - "path" :/\.(png|gif|jpg|jpeg)/, - "localFile" :"/Users/Stella/tmp/test.png", - "localDir" :"~/" - } - ]; +var LOCAL_IMAGE = "/Users/path/to/image.png"; module.exports = { + + //mark if use local response shouldUseLocalResponse : function(req,reqBody){ - var host = req.headers.host, - urlPattern = url.parse(req.url), - path = urlPattern.path; - - for(var index in map){ - var rule = map[index]; - - var hostTest = new RegExp(rule.host).test(host), - pathTest = new RegExp(rule.path).test(path); - - if(hostTest && pathTest && (rule.localFile || rule.localDir) ){ - var targetLocalfile = rule.localFile; - - //localfile not set, map to dir - if(!targetLocalfile){ //find file in dir, /a/b/file.html -> dir + b/file.html - var remotePathWithoutPrefix = path.replace(new RegExp(rule.path),""); //remove prefix - targetLocalfile = pathUtil.join(rule.localDir,remotePathWithoutPrefix); - } - - if(fs.existsSync(targetLocalfile)){ - console.log("==>local file: " + targetLocalfile); - req.replaceLocalFile = targetLocalfile; //add a flag to req object - return true; - } - } + if(/\.(png|gif|jpg|jpeg)$/.test(req.url)){ + req.replaceLocalFile = true; + return true; + }else{ + return false; } - return false; }, dealLocalResponse : function(req,reqBody,callback){ if(req.replaceLocalFile){ - callback(200, {"content-type":"image/png"}, fs.readFileSync(req.replaceLocalFile) ); + callback(200, {"content-type":"image/png"}, fs.readFileSync(LOCAL_IMAGE) ); } } };