小编典典

使用node.js下载图像

node.js

我正在尝试编写一个脚本来使用node.js下载图像。这是我到目前为止的内容:

var maxLength = 10 // 10mb
var download = function(uri, callback) {
  http.request(uri)
    .on('response', function(res) {
      if (res.headers['content-length'] > maxLength*1024*1024) {
        callback(new Error('Image too large.'))
      } else if (!~[200, 304].indexOf(res.statusCode)) {
        callback(new Error('Received an invalid status code.'))
      } else if (!res.headers['content-type'].match(/image/)) {
        callback(new Error('Not an image.'))
      } else {
        var body = ''
        res.setEncoding('binary')
        res
          .on('error', function(err) {
            callback(err)
          })
          .on('data', function(chunk) {
            body += chunk
          })
          .on('end', function() {
            // What about Windows?!
            var path = '/tmp/' + Math.random().toString().split('.').pop()
            fs.writeFile(path, body, 'binary', function(err) {
              callback(err, path)
            })
          })
      }
    })
    .on('error', function(err) {
      callback(err)
    })
    .end();
}

但是,我想使它更强大:

  1. 有图书馆这样做并且做得更好吗?
  2. 响应头是否有可能说谎(关于长度,关于内容类型)?
  3. 我还应该关注其他状态代码吗?我应该麻烦重定向吗?
  4. 我想我读过某个地方binary会不赞成使用编码。那我该怎么办?
  5. 我怎样才能在Windows上使用它?
  6. 还有其他方法可以使此脚本更好吗?

原因:对于类似于imgur的功能(用户可以给我一个URL),我下载了该图像,然后以多种尺寸重新托管该图像。


阅读 287

收藏
2020-07-07

共1个答案

小编典典

我建议使用request模块。下载文件与以下代码一样简单:

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

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});
2020-07-07