nodejs 大文件下载
时间: 2023-08-28 13:04:19 浏览: 43
在 Node.js 中,可以使用 `http` 或 `https` 模块来下载大文件。以下是一个示例代码:
```javascript
const https = require('https');
const fs = require('fs');
const fileUrl = 'https://example.com/largefile.zip';
const filePath = '/path/to/largefile.zip';
const file = fs.createWriteStream(filePath);
https.get(fileUrl, response => {
const totalSize = response.headers['content-length'];
let downloadedSize = 0;
response.on('data', chunk => {
downloadedSize += chunk.length;
const progress = downloadedSize / totalSize * 100;
console.log(`Downloaded ${progress.toFixed(2)}%`);
file.write(chunk);
});
response.on('end', () => {
console.log('Download completed');
file.end();
});
});
```
在上面的代码中,我们使用 `https.get` 方法请求文件,并将其写入到本地文件系统中。我们还通过监听 `response` 对象上的 `data` 事件来获取下载数据的进度。
注意,如果下载的文件非常大,我们可能需要将其分成多个小块进行下载,以避免 Out of Memory 错误。这可以通过使用 `Range` header 和 `http` 或 `https` 模块的 `options` 参数来实现。