upload a file from aws lambda to aws s3 -without using aws-sdk

179 Views Asked by At

I want to perform some lambda function to upload files to s3. I found that using aws-sdk taking too much space for me. so i try to upload with pure node without any libary that not build in.

this is the code that run on aws lambda function:

//My file:
const buffer = await downloadFile(url); // file is gz file downloaded as buffer

    const endpoint = `https://${myBucket}.s3.${myRegion}.amazonaws.com/${store}/${file_name}.gz`;
    const options = {
      method: "PUT",
      headers: {
        "Content-Encoding": "gzip",
        "Content-Length": Buffer.byteLength(buffer),
        "Content-Type": "application/octet-stream",
      },
    };

const data = await uploadFile(endpoint, options, buffer);

and the upload function is :

const uploadFile = (endpoint, options, buffer) => {
  const s3UploadRequest = https.request(endpoint, options, (res) => {
    console.log(`Status code: ${res.statusCode}`);
    console.log(`Status message: ${res.statusMessage}`);
    res.on("data", (chunk) => {
      console.log(`Response: ${chunk}`);
    });
    res.on("end", () => {
      if (res.statusCode > 400 && res) console.log("Upload FAILED");
      else console.log("Upload complete");
    });
  });

  s3UploadRequest.on("error", (error) => {
    console.error(`Error uploading to S3: ${error}`);
  });

  s3UploadRequest.write(buffer);
  s3UploadRequest.end();
};

and im getting "AccessDeniedAccess DeniedsomeIdidLc/largeStringWithManyChars="

The issue is when i run this code using aws-sdk it works fine , but i dont know how to make a simple upload without this libary. (also used documention aws_doc but didnt help me)

0

There are 0 best solutions below