Nodejs 如何批量获取远程图片并显示出来?
Nodejs 如何批量获取远程图片并显示出来?
当我请求远程图片的时候用createWriteStream单个请求没问题,,请求多了,就会出现延迟加载,,谁有更好的方法啊?贴上我的代码.我用的是ruby coffeescript的语法.
request = require 'superagent'
request
.get('mp.weixin.qq.com/cgi-bin/getheadimg?fakeid=' + options.takeid)
.set('Cookie', cookie)
.end (res) ->
filename = __basename + '/public/avatar/'+options.takeid+'.jpg'
f = fs.createWriteStream(filename,
flags: "w"
encoding: "binary"
)
res.on "data", (data) ->
f.write data
options.res.write data
res.on "end", (data) ->
f.end()
options.res.end()
3 回复
Node.js 如何批量获取远程图片并显示出来?
当你需要批量下载远程图片时,使用 createWriteStream
单个请求是没有问题的。但是,当请求数量增加时,可能会遇到延迟加载的问题。本文将介绍如何使用 Node.js 批量高效地获取远程图片,并将其显示出来。
示例代码
首先,我们需要安装一些必要的依赖库:
npm install request request-promise fs-extra
然后,我们可以编写以下示例代码来批量下载远程图片:
const requestPromise = require('request-promise');
const fs = require('fs-extra');
async function downloadImages(imageUrls, outputDir) {
try {
await Promise.all(
imageUrls.map(async (url, index) => {
const response = await requestPromise({
uri: url,
encoding: null // 保持二进制响应
});
const filename = `${outputDir}/image_${index}.jpg`;
await fs.outputFile(filename, response);
console.log(`Downloaded ${url} to ${filename}`);
})
);
console.log('All images downloaded successfully.');
} catch (error) {
console.error('Error downloading images:', error);
}
}
// 示例URL数组
const imageUrls = [
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
'http://example.com/image3.jpg'
];
// 指定输出目录
const outputDir = './images';
// 调用函数下载图片
downloadImages(imageUrls, outputDir);
代码解释
-
引入依赖:
request-promise
: 提供了request
的 promise 版本,方便处理异步操作。fs-extra
: 提供了更丰富的文件系统操作功能。
-
定义
downloadImages
函数:- 接受一个图片 URL 数组和一个输出目录作为参数。
- 使用
Promise.all
并行处理所有图片的下载任务。 - 对于每个 URL,使用
requestPromise
发送 GET 请求,并设置encoding: null
以保持响应为二进制格式。 - 将下载的图片保存到指定的输出目录中。
-
调用
downloadImages
函数:- 提供一个示例的图片 URL 数组和输出目录路径。
- 调用该函数开始下载图片。
通过这种方式,你可以高效地批量下载远程图片,并确保不会因为请求过多而出现延迟加载的问题。
可不可以不用fs,直接显示?
var getHeadImage = function (takeid, cookie) {
return function (request, response, next) {
var url = 'mp.weixin.qq.com/cgi-bin/getheadimg?fakeid=' + takeid;
var output = function (res) {
var image = '';
res.setEncoding('binary');
res.on('data', function (chunk) {
image += res.statusCode == 200 ? chunk : "";
});
res.on('end', function () {
response.writeHead(200, {
'Content-type': res.headers['content-type']
});
response.write(image, 'binary');
response.end();
});
};
superagent.get(url).set('Cookie', cookie).end(output);
}
};
在Node.js中批量获取远程图片并显示出来可以使用axios
或node-fetch
来简化HTTP请求,并结合fs
模块来处理文件操作。以下是一个使用axios
的示例代码,它能更高效地批量下载远程图片:
const axios = require('axios');
const fs = require('fs');
const path = require('path');
// 假设这里有一个包含所有图片URL的数组
const imageUrls = [
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
// 更多图片URL...
];
async function downloadImages() {
for (let url of imageUrls) {
try {
const response = await axios({
method: 'GET',
url: url,
responseType: 'stream',
});
const filename = path.basename(url);
const writer = fs.createWriteStream(filename);
response.data.pipe(writer);
writer.on('finish', () => {
console.log(`${filename} 已保存`);
});
writer.on('error', (err) => {
console.error(`写入文件失败: ${err.message}`);
writer.end();
});
} catch (err) {
console.error(`下载图片失败: ${err.message}`);
}
}
}
downloadImages().catch(console.error);
解释
- axios: 一个流行的HTTP客户端库,用于发送网络请求。
- fs: Node.js内置的文件系统模块,用于文件操作。
- path: Node.js内置的路径模块,用于处理和转换文件路径。
该脚本通过循环遍历图片URL列表,逐个请求每个URL并将响应数据流直接写入到本地文件。这种方法避免了手动处理data
事件中的缓冲区问题,并提高了代码的可读性和效率。