Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
http port forward for nodejs,ie access jenkins by http://yourhostname/jenkins,which located at http://yourhostname:8080/jenkins
'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
You can’t perform that action at this time.