用NodeJS检索远程文件进行存储?

我有NodeJS restify安装程序,我正在使用mongoose附件将图像附加到我的用户模型,并将图像存储在S3存储桶中。

我还允许用户使用Passport.JS使用Facebook,Google等进行注册。

问题是mongoose-attachments在调用.attach()函数时需要本地文件引用,PassportJS提供了一个远程URL – 所以我需要下载图像,然后从tmp附加它。

我应该如何用NodeJS来解决这个问题? 有没有一个好的模块,我可以用这个?

我设法find一个工作的解决scheme,通过请求模块。 它做我所需要的,它似乎是任何Web应用程序的一个完善的工具。 这是工作的代码:

var userImageProp = {}; if ((profile.picture) && (profile.picture.data.is_silhouette == false)) { var pictureURL = 'https://graph.facebook.com/'+ profile.id +'/picture?type=large'; // Determine file name. var filename = profile.picture.data.url.replace(/^.*[\\\/]/, ''); // Precreate stream and define callback. var picStream = fs.createWriteStream('/tmp/'+filename); picStream.on('close', function() { console.log('Downloaded '+filename); userImageProp.path = '/tmp/'+filename; finishSave(user, userImageProp); }); // Get and save file. request(pictureURL).pipe(picStream); } else { userImageProp.path = config.root + '/defaults/img/faceless_'+user.gender.toLowerCase()+'.png'; finishSave(user, userImageProp); } function finishSave(user, userImageProp) { user.attach('userImage', userImageProp, function(err) { console.dir(err); if (err) { return done(new restify.InternalError(err)); } user.save(function (err, user) { if (err) { return done(new restify.InternalError(err)); } // Saved successfully. Return user for login, and forward client to complete user creation. return done(null, user, '/#/sign-up/facebook/save'); }); }); } 

感谢这些线索帮助我想出这个解决scheme:

  • Facebook API – 如何通过Facebook API获取Facebook用户的个人资料图片(无需用户“允许”该应用程序)

  • 图像下载后的callbackfunction

  • 如何从使用JavaScript的完整path获取文件名?

你看看mongoose附件-aws2js