Avinash Prabhakar
Avinash Prabhakar

Reputation: 483

Displaying an image on API endpoint using aws lambda and node.js

Right now I am editing the code inline on AWS lambda. This is what I have currently:

var qrImage = require('qr-image');


exports.handler = async (event) => {
    return sendRes(200,'hi');
};
/*
const sendRes = (status, body) => {
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "text/html"
    },
    body: body
  };
  return response;
}; 
*/

const sendRes = (status, body) => {
  const svg_string = qrImage.imageSync('http://www.nodejs.org',{ type: 'png', size: 20 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/jpeg"
    },
    body: svg_string
  };
  return response;
};

This outputs the text Internal server error.

The code below creates a png file and stores it. The functionality I would like on lambda is to simply display the image(No saving involved) when I access the endpoint. But I am not sure how to go about it (New to Lamda, Node.js). What exactly should I be looking into?

var qrImage = require('qr-image');
var fs = require('fs');

qrImage
    .image("http://www.nodejs.org", {type:'png', size:20})
    .pipe(fs.createWriteStream("MyQRCode.png"));

EDIT I made some small changes and this appears to be working

var qrImage = require('qr-image');

exports.handler = async (event) => {
    return sendRes(200,'hi');
};

const sendRes = (status, body) => {
  const svg_string = qrImage.imageSync('this is AWS!', { type: 'svg', size: 10 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/svg+xml"
    },
    body: svg_string
  };
  return response;
};

Upvotes: 1

Views: 977

Answers (1)

Sanket
Sanket

Reputation: 985

If you are only returning the image with the help of lambda then sync will also work, here the code for it

const sendRes = (status, body) => {
  const svg_string = qr.imageSync('http://www.nodejs.org', { type: 'png', size: 20 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/jpeg"
    },
    body: svg_string
  };

  return response;
};

Upvotes: 1

Related Questions