Skip to content

Puppeteer download file: four ways to save files in Node.js

Saving a file through Puppeteer looks trivial until the script exits before anything lands on disk, or the 'download' turns out to be an XHR the browser never treats as a file. This guide compares four approaches that each fit a different site behaviour, and shows how to tell a finished download from a click that merely fired.

Quick answer

If a page has a real download button, the shortest path is: point Chrome at a folder you control, allow browser-managed downloads, click, then wait until a real file exists on disk. Use the CDP download events when you need progress or reliable success/failure signals. Use in-page fetch when the page can retrieve the file itself, and use Axios/HTTPS streaming when you already have a direct file URL and many files to fetch.

Decision checklist: which method fits your site

Before writing code, classify the site. Each row below maps an observable behaviour to the method that handles it best.

Setup: project, Chromium, and a controlled download folder

Use Node 20+ with ESM. Puppeteer bundles a Chrome for Testing build during install; if you need to skip that download in a restricted environment, set PUPPETEER_SKIP_DOWNLOAD. Before touching downloads, confirm Puppeteer launches and can read a page title. Then create an absolute download path — Chrome requires absolute paths — and allow downloads via Browser.setDownloadBehavior with behavior: 'allow' and your downloadPath. Some sites hide download buttons on mobile layouts, so setting a desktop User-Agent and a 1280x800 viewport avoids missing-button surprises. Note that headless: 'shell' can behave differently for browser-managed downloads; the examples here assume the default headless mode.

Method 1: click the button, then wait for a real file

Open the page, wait for the download control to be visible, scroll it into view, and click. The hard part is the wait. A filename appearing is not proof of completion: Chrome writes temporary .crdownload files first, and on Windows you can see ghost events or files that vanish. A more dependable pattern is to snapshot the folder before clicking, poll for newly added files, ignore .crdownload, require a non-zero size, and require the size to stay unchanged across several checks before treating the file as done. Always set a timeout so a stuck download fails loudly instead of hanging. Filesystem checks are heuristic; for parallel downloads, overwrites, or progress reporting, use the CDP events in Method 3. Avoid the OS default Downloads folder: it may already contain files, permissions vary between machines, and CI runners or containers may not have a writable Downloads directory at all.

Method 2: fetch inside the page and save from Node.js

Here Chrome never performs a download. Inside page.evaluate you call fetch() on the file URL, read the response as a Blob, convert it to a base64 data URL, and return only the base64 payload. Puppeteer can only return serializable values, so raw ArrayBuffer, Uint8Array, or binary cannot cross the boundary — base64 is the workaround. Back in Node.js, Buffer.from(fileBase64, 'base64') restores the bytes and fs.writeFile saves them under a filename you choose. This works for images, PDFs, ZIPs, and other binary files. Two limits matter: CORS and same-origin rules still apply inside the page, so the page must be allowed to fetch that URL; and a single large base64 string is CPU- and memory-heavy. For medium files, return base64 in chunks (for example 256 KiB slices) and write each decoded chunk through a Node write stream. That reduces memory pressure but still loads the whole response in the browser, so it is not true network streaming.

Method 3: listen to Chrome's own download events

Method 1 uses CDP passively — just to allow downloads. Here CDP becomes active. Open a session with page.createCDPSession(), call Browser.setDownloadBehavior with eventsEnabled: true, then subscribe to Browser.downloadWillBegin and Browser.downloadProgress before clicking. The begin event carries guid and suggestedFilename; progress events carry state, receivedBytes, and totalBytes. Resolve on state 'completed', reject on 'canceled', and keep a hard timeout. This gives you progress indicators, clear success/failure signals, and metrics you can log. One caveat: 'completed' does not guarantee the file is flushed and renamed on disk. Verify the file exists and its size stops changing, and fall back to the newest file created since you clicked if the suggested filename is missing or wrong. If you run parallel downloads, consider behavior: 'allowAndName' with the GUID mapping.

Method 4: extract URLs with Puppeteer, download with Axios or HTTPS

Use Puppeteer only for rendering, running site JavaScript, and pulling the real file URLs out of the DOM. Then let Node.js stream the bytes. With Axios, set responseType: 'stream', a request timeout, a redirect limit, and a status validator; check the Content-Type and refuse to save text/html so an error page never becomes your file. Pipe response.data into fs.createWriteStream. https.get works the same way. This is the fastest and most scalable pattern for batches, galleries, and large files. It only works when the URL can be fetched directly — signed links that expire quickly, POST-generated downloads, or links that need cookies and auth headers from inside the browser will push you back to Method 2 or 3. Do not fire dozens of downloads at once: sequential for...of with await is a safe default, and a concurrency limit of 3–5 is a reasonable step up. In production, add retries with backoff and derive file extensions from Content-Type rather than hard-coding them.

Field and control map

Use this map when reading the code examples. Browser.setDownloadBehavior accepts behavior ('allow' or 'allowAndName'), downloadPath (an absolute path), and eventsEnabled (true to receive download events). Browser.downloadWillBegin provides guid, suggestedFilename, and url. Browser.downloadProgress provides guid, state ('inProgress', 'completed', or 'canceled'), receivedBytes, and totalBytes. On the Node side, the wait helpers use timeoutMs, stableChecks, and intervalMs. In the Axios downloader, responseType, timeout, maxRedirects, validateStatus, and the User-Agent/Accept headers are the knobs that matter.

Worked example: one photo page, one file

The examples use an Unsplash photo page whose free-download control is an anchor with data-testid="non-sponsored-photo-download-button". In the captured run for Method 3, the download began with suggestedFilename alexander-grey-tn57JI3CewI-unsplash.jpg, progressed to 2,754,606 of 2,754,606 bytes, and then reported state 'completed'. The script then confirmed the file on disk at the configured download folder. That sequence is the useful lesson: the filename and byte counts come from Chrome's events, and the disk check is what turns 'completed' into a verified file path. In the gallery example, some photo pages had no free download button and were skipped rather than failing the whole run.

Why a download looks stuck

Two failure modes dominate. First, the script closes the browser or exits before the asynchronous download finishes — the click succeeded but nothing was awaited. Second, the 'download' is actually a navigation or an XHR, so no browser-managed download ever starts and no file appears. The fix in both cases is to wait on a real signal: a stable file on disk, a CDP 'completed' event, or a resolved fetch. Wrap the patterns in reusable helpers so each script does not re-implement the same polling logic.

Method selection by site behaviour
What you observeBest methodWhy
Visible button triggers a real browser downloadMethod 1 (click + wait)Simplest; Chrome handles the file, you only verify it landed
Download is fetched by XHR/fetch, no browser downloadMethod 2 (in-page fetch)You read the bytes yourself and control the filename
Need progress, cancellation, or reliable success signalsMethod 3 (CDP events)Chrome reports lifecycle events instead of you guessing from the folder
You have a direct file URL and many filesMethod 4 (Axios/HTTPS stream)Fastest and most scalable; streams to disk without browser UI
Signed link that expires, POST-generated, or needs in-browser cookiesMethod 2 or 3A plain Node request will not carry the browser context

Behaviour categories are descriptive; a site may combine several.

Frequently asked questions

How do I choose the best method to download a file with Puppeteer?

Match the method to what the site exposes. A real button that triggers a browser download needs only a click plus a wait. A direct file URL can be fetched inside the page or downloaded with Axios from Node.js. If you need progress, error states, or production-grade reliability, use CDP. For many files or large downloads, the hybrid Puppeteer + Axios approach scales best.

Why is my Puppeteer file download stuck or never finishing?

Usually the script exits before the download completes; browser downloads are asynchronous and need an explicit wait. Another common cause is that the 'download' is really a navigation or an XHR, so no browser-managed download ever starts. Wait on a completion signal — filesystem checks or CDP events — and confirm the file exists on disk.

Can I avoid running Chrome and still download files from dynamic pages?

Partly. You can use Puppeteer only to extract the real file URLs and then download with Node.js via Axios or HTTPS. If the page depends heavily on JavaScript execution, authentication, or protected endpoints, you still need a browser or a rendering service.

How does Puppeteer compare to Playwright for file downloads?

Both handle downloads well. Puppeteer stays closer to the Chrome DevTools Protocol, which makes low-level download control and debugging more explicit. Playwright offers a higher-level API and broader cross-browser support. For download logic alone, the choice usually comes down to ecosystem familiarity and team preference.

"type": "module"