AWS S3 Ошибка создания узла лямбда-эскиза в облаке - PullRequest
0 голосов
/ 07 января 2020

Моя лямбда-функция не генерирует миниатюры, как ожидалось. Вот мой код node . Я загрузил файл .zip с модулями узла.

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm')
            .subClass({ imageMagick: true }); // Enable ImageMagick integration.
var util = require('util');

// constants
var MAX_WIDTH  = 250;
var MAX_HEIGHT = 250;

// get reference to S3 client
var s3 = new AWS.S3();

exports.handler = function(event, context, callback) {
    // Read options from the event.
    console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
    var srcBucket = event.Records[0].s3.bucket.name;
    // Object key may have spaces or unicode non-ASCII characters.
    var srcKey    =
    decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
    var dstBucket = srcBucket + "resized";
    var dstKey    = "thumb-" + srcKey;

    // Sanity check: validate that source and destination are different buckets.
    if (srcBucket == dstBucket) {
        callback("Source and destination buckets are the same.");
        return;
    }

    // Infer the image type.
    var typeMatch = srcKey.match(/\.([^.]*)$/);
    if (!typeMatch) {
        callback("Could not determine the image type.");
        return;
    }
    var imageType = typeMatch[1].toLowerCase();
    if (imageType != "jpg" && imageType != "png") {
        callback(`Unsupported image type: ${imageType}`);
        return;
    }

    // Download the image from S3, transform, and upload to a different S3 bucket.
    async.waterfall([
        function download(next) {
            // Download the image from S3 into a buffer.
            s3.getObject({
                    Bucket: srcBucket,
                    Key: srcKey
                },
                next);
            },
        function transform(response, next) {
            gm(response.Body).size(function(err, size) {
                console.log('Width logggg' + size.width);
                console.log('height logggg' + size.height)
                // Infer the scaling factor to avoid stretching the image unnaturally.
                var scalingFactor = Math.min(

                    MAX_WIDTH / size.width,
                    MAX_HEIGHT / size.height
                );
                var width  = scalingFactor * size.width;
                var height = scalingFactor * size.height;

                // Transform the image buffer in memory.
                this.resize(width, height)
                    .toBuffer(imageType, function(err, buffer) {
                        if (err) {
                            next(err);
                        } else {
                            next(null, response.ContentType, buffer);
                        }
                    });
            });
        },
        function upload(contentType, data, next) {
            // Stream the transformed image to a different S3 bucket.
            s3.putObject({
                    Bucket: dstBucket,
                    Key: dstKey,
                    Body: data,
                    ContentType: contentType
                },
                next);
            }
        ], function (err) {
            if (err) {
                console.error(
                    'Unable to resize ' + srcBucket + '/' + srcKey +
                    ' and upload to ' + dstBucket + '/' + dstKey +
                    ' due to an error: ' + err
                );
            } else {
                console.log(
                    'Successfully resized ' + srcBucket + '/' + srcKey +
                    ' and uploaded to ' + dstBucket + '/' + dstKey
                );
            }

            callback(null, "message");
        }
    );
};

Я только что вставил код из этой ссылки

Я правильно все реализовал в лямбда, триггере S3 и именах сегментов. Но в метрике Cloudwatch я получаю эту ошибку. enter image description here

Пожалуйста, расскажите мне о моей ошибке.

Как исправить эту ошибку.

1 Ответ

0 голосов
/ 07 января 2020

Трассировка стека показывает, что ошибка происходит в файле /var/task/index.js в строке 57, столбце 38, так что это лучшее место для начала.

Если бы мне пришлось угадывать, если мы предполагаем, функция transform - это то, что находится в index.js, возможно, size не имеет свойства width. Возможно, стоит зайти туда, чтобы посмотреть, что происходит.

function transform(response, next) {
            gm(response.Body).size(function(err, size) {
                // Infer the scaling factor to avoid stretching the image unnaturally.
                var scalingFactor = Math.min(
                    MAX_WIDTH / size.width, // <-- here
                    MAX_HEIGHT / size.height
                );

Idk, что gm(response.Body).size() ожидает для своего обратного вызова, но было бы неплохо зарегистрировать передаваемые здесь параметры.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...