Skip to content
jshacks.dev
Node.js

Build a Web Scraper With Node.js

Build a polite web scraper with fetch, timeouts, retries, a concurrency limit, robots.txt checks and a CSV export, using only the standard library.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Node.js, Swagger and NGINX logos.

Most scrapers fail for reasons that have nothing to do with parsing. They hammer a server until it blocks them, hang forever on a connection that never answers, crash on the first 500 and write half a result file. A scraper you can leave running needs timeouts, retries, a limit on how many requests are in flight and respect for the site it reads. This post builds one on Node.js 26 with the global fetch, an AbortSignal for timeouts, a small worker pool and a CSV writer, and it extracts data with a deliberate, narrow approach that you can swap for a parser when the markup gets complicated.

Before you write any code

Scraping is allowed or not depending on the site, so check three things. Read the site's terms of use, because some prohibit automated access. Fetch /robots.txt and respect the paths it disallows for your user agent. And look for an API or a data feed first: a documented JSON endpoint is faster, more stable and more polite than parsing HTML. The sample targets a fictional catalog at https://shop.example/products?page=N that lists products with a name and price. Replace it with a site you have permission to read.

Fetching with a timeout

fetch has no default timeout, so a stalled server holds your scraper forever. AbortSignal.timeout(ms) fixes that in one expression.

http.jsJavaScript
const USER_AGENT = "catalog-scraper/1.0 (contact: [email protected])";

export async function get(url, { timeout = 10_000 } = {}) {
  const res = await fetch(url, {
    headers: { "user-agent": USER_AGENT, accept: "text/html" },
    signal: AbortSignal.timeout(timeout),
    redirect: "follow",
  });
  if (!res.ok) {
    const error = new Error(`HTTP ${res.status} for ${url}`);
    error.status = res.status;
    throw error;
  }
  return res.text();
}

An honest user agent with contact details lets a site owner reach you instead of blocking you, and it is the polite default. The timeout throws a TimeoutError after 10 seconds, which the retry logic below will treat as retryable. Turning a non-2xx status into an error with a status property gives the retry code something to inspect, because fetch itself only rejects on network failure.

Retrying the right errors

Not every failure deserves a retry. A 404 will stay a 404. A 429, a 503 or a timeout are the kind that pass. Retry those, wait longer each time and add a little randomness so a fleet of workers does not retry in lockstep.

retry.jsJavaScript
const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]);

function shouldRetry(error) {
  if (error.status) return RETRYABLE.has(error.status);
  return error.name === "TimeoutError" || error.cause?.code === "ECONNRESET";
}

export async function withRetry(fn, { attempts = 4, baseMs = 500 } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt >= attempts || !shouldRetry(error)) throw error;
      const delay = baseMs * 2 ** (attempt - 1) * (0.5 + Math.random());
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
  }
}

The delay doubles each attempt, from about 500 ms to 1 s to 2 s, with a random factor between 0.5 and 1.5. If the server sent a Retry-After header on a 429, honoring it is better than guessing, and you can read it from the response before throwing. When a request fails with a network error, Node.js fetch wraps the system error in error.cause, which is where ECONNRESET lives.

Limiting concurrency

Fetching 1,000 pages with Promise.all opens 1,000 connections at once, which is rude and often gets you blocked. A fixed pool of workers pulling from a shared queue keeps the load steady.

pool.jsJavaScript
export async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;

  async function worker() {
    while (next < items.length) {
      const index = next++;
      results[index] = await fn(items[index], index);
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

This works without locks because Node.js runs your code on one thread: next++ cannot be interleaved with another worker between the read and the write. Each worker takes the next index, awaits the job and loops. Results keep the input order, which makes the output deterministic even though the work finishes in any order. Add a short delay inside fn, such as 200 ms, if the site asks for a crawl delay.

Respecting robots.txt

Parsing the full robots.txt grammar is a library's job, but the common case, Disallow lines under a matching User-agent, takes a few lines.

robots.jsJavaScript
import { get } from "./http.js";

export async function loadRules(origin) {
  let text = "";
  try {
    text = await get(`${origin}/robots.txt`);
  } catch {
    return () => true;
  }
  const disallowed = [];
  let applies = false;
  for (const raw of text.split("\n")) {
    const line = raw.split("#")[0].trim();
    const [field, ...rest] = line.split(":");
    const value = rest.join(":").trim();
    if (/^user-agent$/i.test(field)) applies = value === "*";
    else if (applies && /^disallow$/i.test(field) && value) disallowed.push(value);
  }
  return (path) => !disallowed.some((prefix) => path.startsWith(prefix));
}

The function returns a predicate. It handles User-agent: * and plain prefix Disallow rules, and it does not understand Allow overrides, wildcards or crawl delays, so treat it as a floor and not a full implementation. If robots.txt cannot be fetched, the sample allows everything, which is the conventional reading for a missing file but is a decision you should make deliberately for each site.

Extracting data

Parsing HTML with regular expressions is fragile in general, and a real parser such as cheerio or linkedom is the right tool for messy pages. For a page with a predictable repeating block, a narrow pattern is dependable and keeps the example dependency-free. Suppose each product is rendered like this:

HTML
<li class="product"><a href="/p/42">Desk Lamp</a> <span class="price">$24.50</span></li>
parse.jsJavaScript
const ITEM = /<li class="product"><a href="([^"]+)">([^<]+)<\/a>\s*<span class="price">\$([\d,.]+)<\/span><\/li>/g;

function decode(text) {
  return text.replaceAll("&amp;", "&").replaceAll("&#39;", "'").replaceAll("&quot;", '"');
}

export function parseProducts(html, base) {
  const out = [];
  for (const match of html.matchAll(ITEM)) {
    out.push({
      url: new URL(match[1], base).href,
      name: decode(match[2].trim()),
      price: Number(match[3].replaceAll(",", "")),
    });
  }
  return out;
}

const sample = '<li class="product"><a href="/p/42">Desk Lamp</a> <span class="price">$24.50</span></li>';
console.log(parseProducts(sample, "https://shop.example"));
Text
[
  {
    url: 'https://shop.example/p/42',
    name: 'Desk Lamp',
    price: 24.5
  }
]

Two habits matter more than the pattern. Resolve relative links against the page address with new URL(href, base), so /p/42 becomes an absolute address. And convert prices to numbers at the edge, so later code never compares strings. If the site changes its markup, the parser returns an empty list. Treat an empty page that should have items as an error and not as "no results", or you will happily export an empty file.

Writing the CSV

CSV looks trivial and has one rule that bites: any field containing a comma, a quote or a newline must be wrapped in quotes, with inner quotes doubled.

csv.jsJavaScript
function cell(value) {
  const text = String(value);
  return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
}

export function toCsv(rows, columns) {
  const lines = [columns.join(",")];
  for (const row of rows) lines.push(columns.map((c) => cell(row[c])).join(","));
  return lines.join("\n") + "\n";
}

console.log(toCsv([{ name: 'Lamp, "XL"', price: 24.5 }], ["name", "price"]));
Text
name,price
"Lamp, ""XL""",24.5

Putting it together

scrape.jsJavaScript
import { writeFile } from "node:fs/promises";
import { get } from "./http.js";
import { withRetry } from "./retry.js";
import { mapLimit } from "./pool.js";
import { loadRules } from "./robots.js";
import { parseProducts } from "./parse.js";
import { toCsv } from "./csv.js";

const ORIGIN = "https://shop.example";
const pages = Array.from({ length: 20 }, (_, i) => `${ORIGIN}/products?page=${i + 1}`);

const allowed = await loadRules(ORIGIN);
const targets = pages.filter((url) => allowed(new URL(url).pathname));

const failures = [];
const results = await mapLimit(targets, 3, async (url) => {
  try {
    const html = await withRetry(() => get(url));
    await new Promise((resolve) => setTimeout(resolve, 300));
    return parseProducts(html, ORIGIN);
  } catch (error) {
    failures.push({ url, error: error.message });
    return [];
  }
});

const products = results.flat();
await writeFile("products.csv", toCsv(products, ["name", "price", "url"]));
console.log(`${products.length} products from ${targets.length} pages, ${failures.length} failed`);
for (const f of failures) console.error(`  ${f.url}: ${f.error}`);

A run against a healthy site prints one summary line.

Text
412 products from 20 pages, 0 failed

The counts depend on the site. Failures are collected rather than thrown, so one bad page does not discard the other nineteen, and the summary tells you exactly what to re-run.

When this approach stops working

Pages that build their content with JavaScript return an empty shell to fetch. Before reaching for a headless browser, open the browser's network panel and look for the JSON request the page makes: calling that endpoint directly is usually simpler and faster. If there is truly no alternative, a browser driver such as Playwright runs a real page, at a much higher cost in memory and time.

Keeping it running

A scraper you run once is a script. One you run every night is a service, and it needs a few more habits. Log every request with its status and duration, so when a site starts returning 403 you can see when it began and whether the change was sudden. A sudden jump to errors means you were blocked. A slow climb in latency means the site is struggling, and you should back off.

Save raw responses while you develop. Writing each HTML page to disk lets you change the parser and re-run it against the saved files, with no new traffic to the site. That is kinder to the server and much faster for you, and it turns a flaky network job into a deterministic one for the part you are actually editing.

Make runs resumable. Write the results of each page as soon as you have them, in a file per page or in an append-only log, and skip pages that already exist on the next run. If the process dies at page 17 of 20, you pay for three pages and not twenty.

Watch for drift. Sites change their markup without telling you, and a parser that silently returns zero items looks exactly like a catalog that emptied out. Compare each run with the last one: if the item count drops by more than, say, half, fail loudly and send an alert. A scraper that fails clearly is more useful than one that quietly writes empty files for a month.

Last, cap the total work. Set a maximum number of pages and a maximum run time, so a pagination bug that loops forever cannot turn into a denial of service against someone else's server.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.