Node.js Aws Lambda:将getObject转换为base64

5
我已经修改了来自这里的zip函数,因为它只能压缩文本而不能压缩图像。

问题出现在代码末尾的base64_encode函数中。我可以将base64字符串写入控制台,但无法将其返回给调用函数。

欢迎任何帮助。

let AWS = require('aws-sdk');
let JSZip = require("jszip");
let fs = require("fs");
const s3 = new AWS.S3();
let thebase='';


exports.handler = function (event, context, callback) {
    let myzip = event.zip;
    let modified = 0, removed = 0;
    let mypath = event.path;
    let mynewname = event.newname;
    let filename = event.filename;

 //get Zip file
    s3.getObject({
        'Bucket': "tripmasterdata",
        'Key': event.path+'/'+myzip,
       
    }).promise()
        .then(data => {
            let jszip = new JSZip();
            jszip.loadAsync(data.Body).then(zip => {
                // add or remove file
                if (filename !== '') {
                      //here I get the Image to be stored in the zip as base64 encoded string
                      thebase = base64_encode(mypath,filename,thebase);
                      console.log('AD:'+thebase); //<- this is always empty, WHY????
                      zip.file(mynewname, thebase, {createFolders: false,compression: "STORE",base64: true});
                      modified++;
                } else {
                      console.log(`Remove ${filename}`);
                      zip.remove(filename);
                      removed++;
                }

                let tmpzip = `/tmp/${myzip}`
                let tmpPath = `${event.path}`
                //Generating the zip
                console.log(`Writing to temp file ${tmpzip}`);
                zip.generateNodeStream({ streamFiles: true })
                    .pipe(fs.createWriteStream(tmpzip))
                    .on('error', err => callback(err))
                    .on('finish', function () {
                        console.log(`Uploading to ${event.path}`);
                        s3.putObject({
                            "Body": fs.createReadStream(tmpzip),
                            "Bucket": "xxx/"+tmpPath,
                            "Key": myzip,
                            "Metadata": {
                                "Content-Length": String(fs.statSync(tmpzip).size)
                            }
                        })
                            .promise()
                            .then(data => {
                                console.log(`Successfully uploaded ${event.path}`);
                                callback(null, {
                                    modified: modified,
                                    removed: removed
                                });
                            })
                            .catch(err => {
                                callback(err);
                            });
                    });
            })
                .catch(err => {
                    callback(err);
                });
        })
        .catch(err => {
            callback(err);
        });
}
//function that should return my base64 encoded image
function base64_encode(path,file,thebase) {
    var leKey = path+'/'+file;
    var params = {
    'Bucket': "xxx",
        'Key': leKey
    }
   s3.getObject(params, function(error, data) {
        console.log('error: '+error);
      }).promise().then(data => {
         thebase = data.Body.toString('base64');
         console.log('thebase: '+thebase); //<- here I see the base64 encoded string
         return thebase; //<- does not return thebase
       });
      return thebase; //<- does not return thebase
}

1个回答

2

这是一个与Promise相关的问题,函数中的最后一次调用'return thebase;'很可能会返回undefined,因为Promise在函数返回时还没有解决。我发现使用关键字async和await非常有用,这样可以将代码压缩成更易读的格式(它大大简化了代码)。

function base64_encode(path,file,thebase) {
  var leKey = path+'/'+file;
  var params = {
    'Bucket': "xxx",
    'Key': leKey
  }
  return s3.getObject(params).promise();
}

那么在主函数中,您需要使用.then()来处理Promise。

如果您正在使用async/await,则代码如下所示:

async function base64_encode(path,file,thebase) {
  var leKey = path+'/'+file;
  var params = {
    'Bucket': "xxx",
    'Key': leKey
  }
  return s3.getObject(params).promise();
}

let thebase = await base64_encode('stuff');

希望这能有所帮助。

非常好,确实那就是问题所在。非常感谢您的帮助。 - CaptainMik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接