Doing http requests through a SOCKS5 proxy in NodeJS

Fredefl picture Fredefl · Jul 17, 2012 · Viewed 33.2k times · Source

I'm planning to do a series of HTTP requests in NodeJS though Tor.
Tor uses SOCKS5 so I went out and searched for a way to proxify HTTP requests in NodeJS.
I'm planning to the the default http.request() function to do the work.
However, I can't seem to find a way to use a proxy with that.
Someone suggested that I could do this:

var http = require("http");
var options = {
  host: "localhost",
  port: 9050,
  path: "http://check.torproject.org",
  method: 'GET',
  headers: {
    Host: "http://check.torproject.org",
  }
};
var req = http.request(options, function(res) {
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

But it didn't work.
So, any suggestions?

Answer

Matthew picture Matthew · Mar 5, 2013

I've just published two modules that should help you do this: socks5-http-client and socks5-https-client.

Just use those instead of the default http module. The API is the same. For example:

require('socks5-http-client').request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
});