'AWS S3 list all objects by object created/modified date descending order NodeJs

I'm using NodeJs to list of objects in a S3 bucket by created/modified object date descending order but not finding any option to pass descending order option

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

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

// Create the parameters for calling listObjects
var bucketParams = {
 Bucket : 'BUCKET_NAME',
};

// Call S3 to obtain a list of the objects in the bucket
s3.listObjects(bucketParams, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});


Solution 1:[1]

Per Amazon docs the list will return the objects in UTF-8 character encoding in lexicographical order and there's no way to ask for the results to return in a different sorting.

You'll have to sort the results by yourself:

s3.listObjects(bucketParams, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data.Contents.sort(o => o.Key)); // example
  }
});

UPDATE

listObjectsV2 is the recommended approach, from the docs:

const params = {
  Bucket: 'STRING_VALUE', /* required */
  ContinuationToken: 'STRING_VALUE',
  Delimiter: 'STRING_VALUE',
  EncodingType: url,
  ExpectedBucketOwner: 'STRING_VALUE',
  FetchOwner: true || false,
  MaxKeys: 'NUMBER_VALUE',
  Prefix: 'STRING_VALUE',
  RequestPayer: requester,
  StartAfter: 'STRING_VALUE'
};
s3.listObjectsV2(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1