Created
May 21, 2015 18:41
-
-
Save Bonuspunkt/6902190baad63c6ec5e5 to your computer and use it in GitHub Desktop.
SavePage Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var http = require('http'); | |
var path = require('path'); | |
var url = require('url'); | |
var zlib = require('zlib'); | |
var ROOT = __dirname; | |
var persited = [] | |
function generatePath(parts) { | |
var part = ROOT; | |
parts.forEach(function(p, i, a) { | |
part = path.resolve(part, p); | |
if (!fs.existsSync(part) && i !== a.length - 1) { | |
fs.mkdirSync(part); | |
} | |
}) | |
return part; | |
} | |
function proxy(svrReq, svrRes) { | |
var options = url.parse(svrReq.url); | |
options.method = svrReq.method; | |
options.headers = svrReq.headers; | |
var cliReq = http.request(options, function(cliRes) { | |
svrRes.writeHead(cliRes.statusCode, cliRes.headers); | |
var parts = options.pathname | |
.split(/\//g) | |
.filter(function(part) { return part; }); | |
parts.unshift(options.hostname) | |
var filePath = generatePath(parts); | |
console.log(filePath) | |
if (persited.indexOf(filePath) === -1) { | |
var fileStream = fs.createWriteStream(filePath); | |
var pipe = cliRes; | |
if (cliRes.headers['content-encoding'] === 'gzip') { | |
pipe = cliRes.pipe(zlib.createGunzip()); | |
} | |
pipe.pipe(fileStream); | |
} | |
cliRes.pipe(svrRes); | |
cliRes.on('error', function(e) { console.log('cliRes error', e); }); | |
}); | |
svrReq.pipe(cliReq); | |
svrReq.on('error', function(e) { console.log('svrReq error', e); }); | |
svrRes.on('error', function(e) { console.log('svrRes error', e); }); | |
cliReq.on('error', function(e) { console.log('cliReq error', e); }); | |
} | |
http.createServer(function(req, res) { | |
proxy(req, res); | |
}).listen(8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment