Node.js 中下载图片可以通过多种方式实现,以下是一个使用 http
或 https
模块以及 fs
模块的示例:
以下是一个简单的示例,展示如何使用 Node.js 下载图片并保存到本地:
const https = require('https'); // 或者使用 require('http') 如果是 http 图片
const fs = require('fs');
const imageUrl = 'https://example.com/image.jpg'; // 替换为你的图片 URL
const outputPath = './downloaded_image.jpg'; // 图片保存路径
const file = fs.createWriteStream(outputPath);
https.get(imageUrl, (response) => {
response.pipe(file); // 将响应流直接管道到文件写入流
file.on('finish', () => {
file.close(); // 关闭文件流
console.log('图片下载完成');
});
}).on('error', (err) => {
fs.unlink(outputPath); // 如果出错,删除已创建的文件
console.error('下载过程中发生错误:', err.message);
});
axios-retry
。通过上述方法,可以在 Node.js 中有效地下载和管理图片资源。
领取专属 10元无门槛券
手把手带您无忧上云