simple-proxy.js 643 B

123456789101112131415161718192021222324
  1. var http = require('http')
  2. , https = require('https')
  3. , server = http.createServer(handler)
  4. , port = +process.argv[2]
  5. , prefix = process.argv[3]
  6. , upstream = process.argv[4]
  7. , calls = 0
  8. server.listen(port)
  9. function handler (req, res) {
  10. if (req.url.indexOf(prefix) != 0)
  11. throw new Error('request url [' + req.url + '] does not start with [' + prefix + ']')
  12. var upstreamUrl = upstream + req.url.substring(prefix.length)
  13. console.log(req.url + ' -> ' + upstreamUrl)
  14. https.get(upstreamUrl, function (ures) {
  15. ures.on('end', function () {
  16. if (++calls == 2)
  17. server.close()
  18. })
  19. ures.pipe(res)
  20. })
  21. }