원격 파일을 받아 디스크에 저장하는 레시피입니다. 이미지·PDF·바이너리 등 모든 종류의 파일에 적용됩니다.
원격 파일을 받아 디스크에 저장하는 레시피입니다. 이미지·PDF·바이너리 등 모든 종류의 파일에 적용됩니다.
# save using the remote filename:
curl -O https://example.com/report.pdf
# save to a specific path, following redirects:
curl -L -o ./out/report.pdf https://example.com/report.pdfimport { writeFile } from 'node:fs/promises';
const res = await fetch('https://example.com/report.pdf');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
await writeFile('report.pdf', buf);import requests
with requests.get('https://example.com/report.pdf', stream=True) as res:
res.raise_for_status()
with open('report.pdf', 'wb') as f:
for chunk in res.iter_content(chunk_size=8192):
f.write(chunk)curl에서 `-O`(대문자)는 URL의 마지막 경로 조각을 파일명으로 써서 저장하고, `-o <경로>`는 원하는 경로·이름으로 저장합니다. 다운로드 링크는 리다이렉트되는 경우가 많으므로 `-L`을 함께 주어 최종 파일까지 따라가세요.
큰 파일은 메모리에 통째로 올리면 위험합니다. `requests`는 `stream=True` + `iter_content`로, Node는 응답 스트림을 파일로 파이프하여 청크 단위로 써야 메모리를 아낄 수 있습니다.
서버가 보내는 `Content-Disposition: attachment; filename="..."` 헤더에 권장 파일명이 들어 있고, `Content-Length`로 전체 크기를 알 수 있어 진행률 표시에 쓸 수 있습니다. 저장 시 서버가 준 파일명을 그대로 신뢰하지 말고 경로 조작(`../`) 방지를 위해 정제하세요.