Introduction to Global Tunnel
Global Tunnel is a robust Node.js module that allows you to easily configure an HTTP proxy for all HTTP and HTTPS requests. This can enhance security and privacy, making it a valuable tool for developers. In this guide, we will introduce various APIs provided by Global Tunnel and provide code snippets for better understanding.
Installing Global Tunnel
npm install global-tunnel-ng
Configuring Global Tunnel
Initialize and configure Global Tunnel with your proxy settings.
const globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: 'proxy.mycompany.com',
port: 8080,
proxyAuth: 'username:password', // optional authentication
sockets: 50 // optional pool size for persistent sockets
});
Making HTTP Requests
Now, all HTTP requests will route through the specified proxy.
const http = require('http');
http.get('http://www.example.com', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
Making HTTPS Requests
HTTPS requests will also route through the proxy:
const https = require('https');
https.get('https://www.example.com', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
Deactivating Global Tunnel
You can deactivate Global Tunnel when needed:
globalTunnel.end();
Using Global Tunnel with Request Module
Combine Global Tunnel with the Request module for more advanced use cases:
const request = require('request');
globalTunnel.initialize({
host: 'proxy.mycompany.com',
port: 8080
});
request('http://www.example.com', (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Real World App Example
Let’s put it all together in a simple real-world app example.
// app.js
const http = require('http');
const globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: 'proxy.mycompany.com',
port: 8080
});
const server = http.createServer((req, res) => {
http.get('http://www.example.com', (proxyRes) => {
let data = '';
proxyRes.on('data', (chunk) => {
data += chunk;
});
proxyRes.on('end', () => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
});
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
This application sets up an HTTP server that fetches data from example.com
through a proxy and then serves that data to the client.
By leveraging Global Tunnel, you ensure all server-side requests are securely routed through your configured proxy, adding an extra layer of security and privacy to your application.
Keep in mind that improper handling of proxy configurations may lead to performance issues or leakage of sensitive information. Always review your proxy settings and use trusted proxy services.
Hash: bd10a357f18d975a5f249b84e3b30815953b02c3cdb321af39bb4e9b0afa19b9