如何使用回调在Node.JS中下载文件?

时间:2017-12-31 16:36:45

标签: javascript node.js

说我有一个像这样的对象数组:

var posts = [ { title: 'Yessss',
    image: 'https://i.redd.it/23ltzgkgax601.jpg' },
  { title: 'Is 37% still a pass?',
    image: 'https://i.imgur.com/78pdycg.png' },
  { title: 'The best feeling there is',
    image: 'https://i.redd.it/z6ldk7wmjd101.jpg' },
  { title: 'I don\'t follow pornhub someone retweeted it ',
    image: 'https://i.redd.it/vsrbwxj8qr9z.jpg' },
  { title: 'Amazing cheating method discovered',
    image: 'http://imgur.com/rvYV93m' },
  { title: 'I hate when this happens.',
    image: 'https://i.redd.it/yx39xt2piv501.jpg' }];

和一个函数makeImgTweets()。它将文本作为参数发布。图像文件的路径是硬编码的,因为我想覆盖它们(不想保留它们)。

function makeImgTweet(text) {
    var b64content = fs.readFileSync("./image.jpg", { encoding: 'base64' })

    Twit.post('media/upload', { media_data: b64content }, function (err, data, response) {
      // now we can assign alt text to the media, for use by screen readers and
      // other text-based presentations and interpreters
      var mediaIdStr = data.media_id_string
      var altText = text
      var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }

      Twit.post('media/metadata/create', meta_params, function (err, data, response) {
        if (!err) {
          // now we can reference the media and post a tweet (media will attach to the tweet)
          var params = { status: text, media_ids: [mediaIdStr] }

          Twit.post('statuses/update', params, function (err, data, response) {
            console.log(data)
          })
        } else {
            console.log(err);
        }
      })
    })            
}

如何遍历帖子中的对象,通过链接下载图像,然后仅在下载图像后调用makeImgTweet函数?

伪代码:

posts.forEach(post) {
    download(post.image) // save to ./image.jpg
    makeImgTweets(post.title); // only run after image is downloaded
}

1 个答案:

答案 0 :(得分:0)

你可能想要使用promises。

function makeImgTweet (text) {
  return new Promise(function (resolve, reject) {
    var b64content = fs.readFileSync("./image.jpg", { encoding: 'base64' })

    Twit.post('media/upload', { media_data: b64content }, function (err, data, response) {
      // now we can assign alt text to the media, for use by screen readers and
      // other text-based presentations and interpreters
      var mediaIdStr = data.media_id_string
      var altText = text
      var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }

      Twit.post('media/metadata/create', meta_params, function (err, data, response) {
        if (!err) {
          // now we can reference the media and post a tweet (media will attach to the tweet)
          var params = { status: text, media_ids: [mediaIdStr] }

          Twit.post('statuses/update', params, function (err, data, response) {
            resolve(data)
          })
        } else {
            reject(err);
        }
      })
    }) 

然后下载您的文件:

var http = require('http');
var fs = require('fs');

function download (url) {
  return new Promise(function (resolve, reject) {
    var file = fs.createWriteStream("./image.jpg");
    var request = http.get(url, function(response) {
      response.pipe(file).on('finish', function () {
         resolve();
      });
    });
  });

并将它们联系起来:

Promise.all(posts.map(function (post) {
  return download(post.image).then(funcion () {
    return makeImgTweet(post.title);
  });
}).then(function (data) {
  // all posts submitted !
  // data is an array with the data result of the twitter api for each post
});