Created
July 14, 2016 14:53
-
-
Save yanfeng42/494690e06487b0f856c91a5beb3af6b0 to your computer and use it in GitHub Desktop.
http port forward for nodejs,ie access jenkins by http://yourhostname/jenkins,which located at http://yourhostname:8080/jenkins
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
'use strict'; | |
/* Sample | |
forward :8087/jenkins to :8080/jenkins. | |
In product,the entityPort can be 80,so u can access jenkins | |
by http://yourhostname/jenkins | |
Good Luck! All Done Just By NodeJS! | |
*/ | |
const routes = { | |
"/jenkins":8080, | |
}; | |
const entityPort = 8087; | |
forward(entityPort, routes); | |
/** | |
* port forward,base uri and prefix. | |
* @param {number} entityPort port to listen,ie:80,8080. | |
* @param {object} routes pefix and port pairs,ie:{"/jenkins":8080}. | |
* @return {object} http.Server. | |
*/ | |
function forward(entityPort,routes){ | |
const http = require('http'); | |
const server = http.createServer((reqS,resS) => { | |
let path = reqS.url; | |
let port = entityPort; | |
for (let routePath in routes) { | |
if (routes.hasOwnProperty(routePath)) { | |
if (path.startsWith(routePath)) { | |
port = routes[routePath]; | |
break; | |
} | |
} | |
} | |
/* forward. */ | |
reqS.pipe(http.request({ | |
port:port, | |
path: reqS.url, | |
method: reqS.method, | |
headers: reqS.headers, | |
}, (resC)=>{ | |
resS.writeHead(resC.statusCode, resC.headers); | |
resC.pipe(resS); | |
})); | |
}).listen(entityPort); | |
return server; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment