Node.js 批量文件下载实战

在日常服务端与全栈开发中,“批量下载文件”是一个极其普遍的业务诉求:抓取爬取图片、离线同步静态资源、备份第三方媒体文件等。

初学者往往认为这很简单:“不就是写个 for 循环,发个 HTTP 请求拿到数据然后 fs.writeFileSync 吗?”

然而,一旦进入海量文件(如数千张图片)或大文件(如数百兆视频/压缩包)的生产场景,这种初级写法会引发一系列灾难:

  1. 内存爆仓(OOM):全量 Buffer 读入内存,V8 垃圾回收停顿甚至直接崩溃;
  2. 并发失控:无脑 Promise.all 瞬间并发数千个 TCP 连接,触发本地 EMFILE: too many open files 错误,同时直接被对方服务端防护判定为 DoS 攻击并封禁 IP;
  3. “假完成”隐形 Bug:对原生 Stream 误用 await stream.pipe(...),程序以为下载完成,实则底层网络流还在传输或已悄然静默中断;
  4. 脏数据碎片残留:网络抖动或中途报错导致磁盘上残留大量只有几 KB 的半截文件,系统无法区分哪些是完好数据。

本文将从底层 Node.js 管道流式传输、滑动窗口并发池、临时原子重命名到指数退避重试,全方位打造一个高可靠、工业级的批量下载引擎。


一、生产环境四大避坑指南

1. 警惕 Stream Pipe 的“伪异步”陷阱

很多开发者习惯这样写流式下载:

1
2
3
// ❌ 严重错误!pipe() 是同步方法,不能直接 await!
await got.stream(url).pipe(fs.createWriteStream(filePath));
console.log('下载完成!'); // 此时数据流可能刚握手,根本没有写完!

stream.pipe() 返回的是目标可写流对象(Writable Stream),它并不是 Promise。因此 await 会立刻返回并继续向下执行,此时磁盘上的文件大小可能是 0 字节!

正确实践:使用 Node.js 官方推荐的 stream/promises 中的 pipeline:

1
2
3
4
5
const { pipeline } = require('stream/promises');
const fs = require('fs');

// ✅ 安全优雅:内部自动处理背压缓冲,监听 finish / error 事件并返回真实 Promise
await pipeline(readableStream, fs.createWriteStream(filePath));

2. 固定分批(Fixed Batching) vs 滑动窗口并发池(Sliding Window Pool)

在控制并发时,一种常见的简单思路是“将数组切块,每次 Promise.all 下载 5 个”:

1
2
3
【固定分批 (Fixed Batching)】低效的“木桶效应”
Batch 1: [文件A (1s)] [文件B (2s)] [文件C (15s卡顿)] ──> 耗时 15s (A/B完成依然干等)
──> 才能启动 Batch 2

如果批次中恰好有一个文件下载极慢(比如耗时 15 秒),其他早已完成的下载槽位只能处于空闲等待状态,导致整体吞吐量严重下降。

最佳实践:滑动窗口并发池(Sliding Window):

1
2
3
4
5
【滑动窗口并发池 (Sliding Window Pool)】保持满载高速
槽位 1: [任务A 1s] ──> [任务D 3s] ──> [任务F 2s] ──> ...
槽位 2: [任务B 2s] ──> [任务E 1s] ──> ...
槽位 3: [任务C (长任务 15s)] ──────────────────────> ...
(任何一个文件下载完成,立刻补位填充下一个,连接永远保持饱和状态!)

3. 原子交付(Atomic Delivery):杜绝半截脏文件

若在下载中途网络中断或报错,直接写入目标文件会导致磁盘残留一个残损的文件。后续重试时系统可能因“文件已存在”误以为下载完成。

最佳实践:

  1. 始终先下载写入临时文件:targetPath + '.tmp';
  2. 整个 Stream 管道成功落盘并关闭后,调用 fs.promises.rename 原子性地重命名为正式目标路径;
  3. 一旦下载报错,捕获异常并主动安全清除 .tmp 临时碎片。

二、方案一:Node.js 原生零依赖极简下载(Node 18+)

得益于 Node.js 18+ 原生内置了全局 fetch 与 Web Streams API,配合标准模块 stream/promises,我们甚至无需安装任何第三方库即可实现高可靠流式下载:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const fs = require('fs');
const path = require('path');
const { pipeline } = require('stream/promises');
const { Readable } = require('stream');

/**
* 原生零依赖流式下载单个文件
* @param {string} url 下载目标地址
* @param {string} destPath 保存的目标路径
*/
async function downloadFileNative(url, destPath) {
const tmpPath = `${destPath}.tmp`;

try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP 异常: ${res.status} ${res.statusText}`);
}

// 确保目标目录存在
await fs.promises.mkdir(path.dirname(destPath), { recursive: true });

// 从 Web ReadableStream 转换为 Node.js 原生流并管道写入
const nodeStream = Readable.fromWeb(res.body);
const fileStream = fs.createWriteStream(tmpPath);

await pipeline(nodeStream, fileStream);

// 下载成功后原子重命名
await fs.promises.rename(tmpPath, destPath);
return true;
} catch (err) {
// 异常时清理半截残损文件
if (fs.existsSync(tmpPath)) {
await fs.promises.unlink(tmpPath).catch(() => {});
}
throw err;
}
}

三、方案二:自研轻量滑动窗口并发控制器

为了在批量处理时精确控制最大并发连接数(如限制最多 5 个任务同时下载),我们可以仅用原生 Promise 封装一个极其轻量的滑动池类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 轻量滑动窗口异步并发执行器
*/
class AsyncPool {
constructor(concurrency = 5) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}

/**
* 提交一个异步任务函数
* @param {() => Promise<any>} taskFn
*/
run(taskFn) {
return new Promise((resolve, reject) => {
this.queue.push({ taskFn, resolve, reject });
this._next();
});
}

_next() {
while (this.running < this.concurrency && this.queue.length > 0) {
const { taskFn, resolve, reject } = this.queue.shift();
this.running++;

Promise.resolve()
.then(taskFn)
.then(resolve)
.catch(reject)
.finally(() => {
this.running--;
this._next();
});
}
}
}

module.exports = AsyncPool;

四、方案三:工业级高可用下载引擎(带重试与进度反馈)

结合现代 HTTP 客户端 got,我们打造一个集成指数退避重试、滑动并发、原子防脏、实时进度追踪的企业级下载器 batch-downloader.js:

1
npm install got

完整核心代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const fs = require('fs');
const path = require('path');
const { pipeline } = require('stream/promises');
const got = require('got');
const AsyncPool = require('./async-pool'); // 引入上方封装的滑动并发池

/**
* 休眠辅助工具
*/
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

/**
* 健壮的流式单文件下载(内置指数退避重试)
* @param {string} url 下载地址
* @param {string} destPath 保存目标全路径
* @param {number} maxRetries 最大重试次数
*/
async function downloadWithRetry(url, destPath, maxRetries = 3) {
const tmpPath = `${destPath}.tmp`;
let attempt = 0;

while (attempt <= maxRetries) {
try {
// 保证目录存在
await fs.promises.mkdir(path.dirname(destPath), { recursive: true });

// 使用 got 构造只读网络流,配置合理超时
const downloadStream = got.stream(url, {
timeout: {
connect: 5000,
response: 10000,
},
retry: { limit: 0 }, // 禁用内部简易重试,由我们统一管理重试生命周期
});

const writeStream = fs.createWriteStream(tmpPath);

// 管道流式传输,自动调节背压
await pipeline(downloadStream, writeStream);

// 原子性重命名为最终交付文件
await fs.promises.rename(tmpPath, destPath);
return { success: true, url, destPath };
} catch (err) {
attempt++;
// 清除未完成的碎片文件
if (fs.existsSync(tmpPath)) {
await fs.promises.unlink(tmpPath).catch(() => {});
}

if (attempt > maxRetries) {
return { success: false, url, error: err.message };
}

// 指数退避:每次重试间隔递增 (1s, 2s, 4s...)
const delay = Math.pow(2, attempt - 1) * 1000;
console.warn(`[重试警报] ${path.basename(destPath)} 下载失败 (${err.message}),将在 ${delay}ms 后进行第 ${attempt}/${maxRetries} 次重试...`);
await sleep(delay);
}
}
}

/**
* 工业级批量文件下载器主入口
* @param {Array<{url: string, filename?: string}>} tasks 下载任务列表
* @param {object} options 配置选项
*/
async function batchDownload(tasks, options = {}) {
const {
outputDir = path.join(__dirname, 'downloads'),
concurrency = 5,
maxRetries = 3,
} = options;

console.log(`\n🚀 开始执行批量下载:总计 ${tasks.length} 个任务,并发限制: ${concurrency}`);
const startTime = Date.now();

const pool = new AsyncPool(concurrency);
let completed = 0;
let succeeded = 0;
let failed = 0;

// 将所有任务映射入滑动并发池
const promises = tasks.map((task, index) => {
const filename = task.filename || path.basename(new URL(task.url).pathname) || `file_${index}`;
const destPath = path.join(outputDir, filename);

return pool.run(async () => {
// 跳过已存在的文件(断点与去重检查)
if (fs.existsSync(destPath)) {
completed++;
succeeded++;
console.log(`[${completed}/${tasks.length}] ⏩ 跳过已存在: ${filename}`);
return { success: true, skipped: true, destPath };
}

const result = await downloadWithRetry(task.url, destPath, maxRetries);
completed++;

if (result.success) {
succeeded++;
console.log(`[${completed}/${tasks.length}] ✅ 成功落盘: ${filename}`);
} else {
failed++;
console.error(`[${completed}/${tasks.length}] ❌ 彻底失败: ${filename} (原因: ${result.error})`);
}
return result;
});
});

const results = await Promise.all(promises);
const totalDuration = ((Date.now() - startTime) / 1000).toFixed(2);

console.log('\n========================================');
console.log(`🎉 批量下载执行完毕 (总耗时: ${totalDuration} 秒)`);
console.log(`📊 统计结果: 成功 ${succeeded} 个, 失败 ${failed} 个, 共计 ${tasks.length} 个`);
console.log('========================================\n');

return results;
}

module.exports = { batchDownload, downloadWithRetry };

五、实测运行示例

创建验证脚本 test-batch.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const path = require('path');
const { batchDownload } = require('./batch-downloader');

const testTasks = [
{ url: 'https://images.unsplash.com/photo-1541701494587-cb58502866ab?w=500', filename: 'art_1.jpg' },
{ url: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=500', filename: 'server_2.jpg' },
{ url: 'https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=500', filename: 'code_3.jpg' },
{ url: 'https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=500', filename: 'matrix_4.jpg' },
{ url: 'https://images.unsplash.com/photo-1518770660439-4636190af475?w=500', filename: 'chip_5.jpg' },
{ url: 'https://images.unsplash.com/photo-1511447333015-45b65e60f6d5?w=500', filename: 'neon_6.jpg' },
];

batchDownload(testTasks, {
outputDir: path.join(__dirname, 'output_images'),
concurrency: 3, // 保持 3 个并发滑动下载
maxRetries: 2,
});

运行输出体验:

1
2
3
4
5
6
7
8
9
10
11
12
🚀 开始执行批量下载:总计 6 个任务,并发限制: 3
[1/6] ✅ 成功落盘: art_1.jpg
[2/6] ✅ 成功落盘: server_2.jpg
[3/6] ✅ 成功落盘: code_3.jpg
[4/6] ✅ 成功落盘: matrix_4.jpg
[5/6] ✅ 成功落盘: chip_5.jpg
[6/6] ✅ 成功落盘: neon_6.jpg

========================================
🎉 批量下载执行完毕 (总耗时: 1.84 秒)
📊 统计结果: 成功 6 个, 失败 0 个, 共计 6 个
========================================

六、进阶架构思考:生产调优要素

  1. HTTP Keep-Alive 连接池复用:在频繁请求相同域名(如某 CDN 图床)时,默认创建新的 TCP 握手与 TLS 协商非常昂贵。可通过在 got 或原生 fetch 中配置自定义 http.Agent 与 https.Agent,开启 keepAlive: true 和设置合理的 maxSockets,显著降低连接握手延迟。
  2. 大文件断点续传(HTTP Range Header):针对体积数 GB 的超大文件,若在 95% 时因网络断开重新从头下载极不合理。可在请求头中附带 Range: bytes=${currentSize}-,仅向服务端请求缺失部分并以追加模式(fs.createWriteStream(tmpPath, { flags: 'a' }))写入。
  3. 磁盘 I/O 吞吐与背压调节:使用 stream/promises.pipeline 的最大价值在于:当本地磁盘繁忙写缓冲区已满时,它会自动暂停接收网络包,从而杜绝由于网络输入过快把内存撑爆的极端情况。

Node.js 批量文件下载实战
https://bubao.github.io/posts/6b6ddd9c.html
作者
一念
发布于
2021年5月22日
许可协议