3

I am writing a lambda function that fetches data from DynamoDB and stores it in an array. Now I want to create a CSV file from this array and return it. (preferably directly from the lambda function, rather than uploading it to s3 and then sharing the link). Any idea, how to do this?

My code until now -

import AWS from "aws-sdk";
import createError from "http-errors";
import commonMiddleware from "../lib/commonMiddleware";

const dynamodb = new AWS.DynamoDB.DocumentClient();

async function getFile(event, context) {
  const { id: someId } = event.pathParameters;
  let data;


  const params = {
    TableName: process.env.TABLE_NAME,
    IndexName: "GSIsomeId",
    KeyConditionExpression: "someId = :someId",
    ExpressionAttributeValues: {
      ":someId": someId,
    },
  };

  try {
    const result = await dynamodb.query(params).promise();
    data = result.Items;
  } catch (error) {
    console.error(error);
    throw new createError.InternalServerError(error);
  }
  
  
  // data is array of objects which I can change to 2d array using Object.values()
  // I want to create and return a CSV from this array 

  return {
    statusCode: 200,
    body: JSON.stringify(data),
  };
}

export const handler = commonMiddleware(getFile);
4
  • I believe this is what you need. stackoverflow.com/a/38245177/6520807 Commented Jul 12, 2021 at 11:51
  • Does this answer your question? How to convert JSON array to CSV using Node.js? Commented Jul 12, 2021 at 11:57
  • @ksaraiya Yes, that would create a CSV file. But how can I send this file in response using AWS Lambda? Commented Jul 12, 2021 at 13:23
  • @ErwinSmithAOT Generate csv data, upload to S3 bucket (pass csv data with filename.csv in params of upload function) and return S3 link in response If you want to download file directly without storing it into S3 bucket then change the response header and return the csv data in response Commented Oct 1, 2021 at 7:45

1 Answer 1

0

Once you generated the csv using any of the approaches mentioned here Convert JSON array to CSV in Node

I guess you can try sending back the byte array of the file.

Sign up to request clarification or add additional context in comments.

2 Comments

any links or references?
You can use some of the Node libraries such as csv-reader or csv-parser

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.