DEV Community

Cover image for Run Node.js scripts from under a TOR / HTTP proxy
Konstantin Tarkus
Konstantin Tarkus

Posted on • Edited on

4 2

Run Node.js scripts from under a TOR / HTTP proxy

Requirements:

$ npm install got socks-proxy-agent cross-spawn --save
Enter fullscreen mode Exit fullscreen mode
const got = require("got");
const spawn = require("cross-spawn");
const { SocksProxyAgent } = require("socks-proxy-agent");

// Launch a TOR proxy via Docker
// @see https://github.com/osminogin/docker-tor-simple
const proxy = spawn("docker", [
  ...["run", "--rm", "-i", "-a", "stdout"],
  ...["-p", "127.0.0.1:9050:9050/tcp"],
  ...["osminogin/tor-simple:latest"],
]);

// Wait until the socks5 proxy server is up and running
proxy.stdout.on("data", (data) => {
  process.stderr.write(data);
  if (data.toString().includes("Opened Socks listener")) {
    run().finally(() => proxy.kill("SIGINT"));
  }
});

// Configure an HTTP client using socks5 proxy
const client = got.extend({
  agent: {
    https: new SocksProxyAgent("socks5://localhost:9050"),
  },
});

// TODO: Write some code that requires a proxy
async function run() {
  const body = await client.get("https://jsonip.com/").json();
  console.log("Client IP:", body.ip);
}
Enter fullscreen mode Exit fullscreen mode

Links

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay