Home > front end >  Nodejs AWS Lambda s3 getObject method returns nothing
Nodejs AWS Lambda s3 getObject method returns nothing

Time:02-25

The script used when trying to get contents from the csv stored in the s3 bucket

const mysql = require("mysql");
const fs = require("fs");
const { google } = require("googleapis");
const AWS = require("aws-sdk");
const client = new AWS.SecretsManager({ region: "eu-west-1" });
const analyticsreporting = google.analyticsreporting("v4");
const csv = require('ya-csv')
const fastCsv = require('fast-csv')



const s3 = new AWS.S3();


const getParams = {
   Bucket: 'data',
   Key:  'athena_test/nameplate.csv'
};

exports.handler = async (context, event)  => {
    
    const data =   await s3.getObject(getParams, function (err, data){
        if(err){console.log("ERROR: ",err)}
        else {return data}
        
     
    

    
})

 console.log(data.Body)  
}

the console log returns undefined rather than the contents of the csv

CodePudding user response:

Hey you can try this one:-

const csv = require('@fast-csv/parse');

const s3Stream = await s3.getObject(params).createReadStream();
const data =  await returnDataFromCSV();
 console.log(data.Body);

const returnDataFromCSV =()=> {
let promiseData = new Promise((resolve, reject) => {
    const parser = csv
      .parseStream(csvFile, { headers: true })
      .on("data", (data) => {
        console.log('Parsed Data:-', data);
      })
      .on("end", ()=> {
        resolve("CSV finished here");
      })
      .on("error",()=> {
        reject("if failed");
      });
  });

  try {
   return await promiseData;
  } catch (error) {
    console.log("Get Error: ", error);
    return error;
  }
}

CreateStream: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#createReadStream-property

  • Related