如何使用本机Node JS HTTP库将图像写入缓冲区? [英] How do I write an image to buffer using native Node JS HTTP library?

查看:93
本文介绍了如何使用本机Node JS HTTP库将图像写入缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript和Node JS的新手。我有各种图像URL,我想缓冲。我已经尝试过请求npm模块,但想要一个更低级别的库来实现我想要实现的目标。

I am really new to JavaScript and Node JS. I have various image URLs that I want to buffer. I have tried the request npm module but want a lower level library for what I want to achieve.

例如:
http://assets.loeildelaphotographie.com/uploads/article_photo/image/128456/_Santu_Mofokeng_-_TOWNSHIPS_Shebeen_Soweto_1987。 jpg

我看到很多示例建议使用请求模块或将文件保存到磁盘的示例。但是,我找不到简单缓冲图像的HTTP GET请求示例,因此我可以传递给另一个函数。它需要有一个结束事件,所以我在另一个步骤中放心地上传缓冲的图像数据。有人可以提供样本模式或如何吗?谢谢!

I see lots of examples that suggest using the request module or examples that save files to disk. However, I cannot find an HTTP GET request example that simply buffers the image so I can pass to another function. It needs to have an "end" event so I upload the buffered image data with confidence in another step. Is there a sample pattern or "how to" on this someone could provide? Thanks!

推荐答案

这是本地方式:

This is the native way:

var http=require('http'), imageBuffer;

http.get(
  'http://www.kame.net/img/kame-anime-small.gif',
  function(res) {
    var body=new Buffer(0);

    if (res.statusCode!==200) {
      return console.error('HTTP '+res.statusCode);
    }

    res.on('data', function(chunk) {
      body=Buffer.concat([body, chunk]);
    });

    res.on('end', function() {
      imageBuffer=body;
    });

    res.on('error', function(err) {
      console.error(err);
    });
  }
);

// Small webserver serving the image at http://127.0.0.1:4567
http.createServer(function(req, res) {
  res.write(imageBuffer || 'Please reload page');
  res.end();
}).listen(4567, '127.0.0.1');

并使用请求( encoding:null for二元响应):

and using request (encoding:null for binary response):

var request=require('request'), imageBuffer;

request({
  uri: 'http://www.kame.net/img/kame-anime-small.gif',
  encoding: null
}, function(err, res, body) {
  if (err) {
    return console.error(err);
  } else if (res.statusCode!==200) {
    return console.error('HTTP '+res.statusCode);
  }
  imageBuffer=body;
});

// Small webserver serving the image at http://127.0.0.1:4567
require('http').createServer(function(req, res) {
  res.write(imageBuffer || 'Please reload page');
  res.end();
}).listen(4567, '127.0.0.1');

这篇关于如何使用本机Node JS HTTP库将图像写入缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆