nodejs 实现网络下载
时间: 2023-11-08 20:51:08 浏览: 157
Node.js可以使用内置的http/https模块实现网络下载。以下是一个简单的示例:
```javascript
const http = require('http');
const https = require('https');
const fs = require('fs');
const fileUrl = 'https://example.com/file.zip';
const savePath = './file.zip';
const download = (url, savePath) => {
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
if (response.statusCode !== 200) {
console.error(`Failed to download ${url}. Status code: ${response.statusCode}`);
return;
}
const fileStream = fs.createWriteStream(savePath);
response.pipe(fileStream);
fileStream.on('finish', () => {
console.log(`${url} downloaded to ${savePath}`);
});
});
};
download(fileUrl, savePath);
```
在此示例中,我们使用http/https模块中的get方法获取文件的响应,并将其管道传输到本地文件流中。当文件流完成写入时,我们将控制台输出下载成功的消息。
阅读全文