Cannot save a file with a specific format name and extension in Bucket

0

Hello everyone! I'm using a lambda function that saves a log into a bucket but I'm having a problem trying to save these files with a specific format name and file extension.

This is my code:

**const createBucket = async (s3, bucket, path, data) => { const putObjectRequest = { // Adds a bucket and key to the body. Bucket: bucket, Key: path, Body: data, ContentType: 'text/plain', }; return s3 .putObject(putObjectRequest) .promise() .then(respo => { return respo; }) .catch(errs => { throw errs; }); } const saveFile = async (bucket, current, date, historyData) => {

  const logName = util.format('ekt-%s_%s000000.log', current.toLowerCase(), date);
  const savedData = await createBucket(
    s3,
    bucket.logs,
    `${current}/${logName}`,
    data
  );

if (!savedData) {
    throw new Error(
      `The file hasn't been created: ${current}/${logName}`
    );
  }
  console.log(`The file has been created: ${current}/${logName}`);

}**

I'm trying to save a file with this format and extension ekt-cp_20230112000000.log but at the end the file is created with this format and extension **ekt-cp_20230112.txt **

I have no clue whats going on!

asked a year ago204 views
1 Answer
0

Hi

I understand you would like to upload a file to s3 using the AWS NodeJS SDK. Below is example code

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'REGION'});

// Create S3 service object
var s3 = new AWS.S3({apiVersion: '2006-03-01'});

// call S3 to retrieve upload file to specified bucket
var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};
var file = process.argv[3];

// Configure the file stream and obtain the upload parameters
var fs = require('fs');
var fileStream = fs.createReadStream(file);
fileStream.on('error', function(err) {
  console.log('File Error', err);
});
uploadParams.Body = fileStream;
var path = require('path');
uploadParams.Key = path.basename(file);

// call S3 to retrieve upload file to specified bucket
s3.upload (uploadParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } if (data) {
    console.log("Upload Success", data.Location);
  }
});

You would call the above code with the following command:

node s3_upload.js BUCKET_NAME FILE_NAME

Please note, you should use the upload API to upload files, and not the createBucket API call. I hope this helps.

AWS
answered a year ago
  • No, I'm not trying to upload a file. I'm creating a new file with data. The file is created correctly except the name and file extension that I'm defining in my code

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions