0

I have a Node.js AWS Lambda function and I am trying to read records from a CSV file in S3 and print its contents.

Below is my code to achieve the same however I am getting Null as output.

Code:

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const csv = require('csv-parser');
const bucket = 'awslambdabuckets';
const objectkey = 'record.csv';
const params = { Bucket: bucket, Key: objectkey };
const results = [];

exports.handler = async function (event, ctx, callback) {
    try {
        const file = s3.getObject(params).createReadStream();

        file
            .pipe(csv())
            .on('data', function (data) {
                results.push;
            })
            .on('end', () => {
                console.log(results);
                callback(null, results);
            });
    } catch (err) {
        console.log(err);
        callback(Error(err));
    }

};

Output: Lambda Output

Can someone help me point out what's the problem and how to fix it.

2
  • 1
    Do not mix async and callback. Use one or the other. Commented Jan 7, 2022 at 15:36
  • Removing async keyword and adding results.push(data); helped solve my problem. Commented Jan 7, 2022 at 15:38

2 Answers 2

2

You are not pushing the data to the result, see and make changes as below

exports.handler = async function (event, ctx, callback) {
  try {
      const file = s3.getObject(params).createReadStream();

      file
          .pipe(csv())
          .on('data', function (data) {
              results.push(data);
          })
          .on('end', () => {
              console.log(results);
              callback(null, results);
          });
  } catch (err) {
      console.log(err);
      callback(Error(err));
  }
};
Sign up to request clarification or add additional context in comments.

Comments

1

You are not pushing data to the array:

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const csv = require('csv-parser');
const bucket = 'awslambdabuckets';
const objectkey = 'record.csv';
const params = { Bucket: bucket, Key: objectkey };
const results = [];

exports.handler = function (event, ctx, callback) {
    try {
        const file = s3.getObject(params).createReadStream();

        file
            .pipe(csv())
            .on('data', function (data) {
                results.push(data); // --> here
            })
            .on('end', () => {
                console.log(results);
                callback(null, results);
            });
    } catch (err) {
        console.log(err);
        callback(Error(err));
    }

};

Comments

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.