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

时间:2013-09-04 21:05:34

标签: node.js mongodb amazon-s3 mongoose passport.js

我有NodeJS restify设置,我正在使用mongoose-attachments将图像附加到我的用户模型,并将图像存储在S3存储桶中。

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

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

我应该如何使用NodeJS来解决这个问题?我可以使用一个很好的模块吗?

2 个答案:

答案 0 :(得分:1)

我设法通过request模块找到了一个有效的解决方案。它做我需要的,它似乎是一个全面的工具,适用于任何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');
        });
    });
}

感谢这些主题帮助我提出这个解决方案:

答案 1 :(得分:0)