Google Cloud Storage сортирует объекты по дате последнего изменения - PullRequest
0 голосов
/ 20 марта 2019

Как отсортировать файлы по дате их последнего изменения? Код ниже просто сортирует их по расширению (json или jpg)

function ambilData(req, res) {
  let hasil;

  ember
  .getFiles(options)
  .then(results => {
    const files = results[0];
    const tempArr = [];
    let jsonArr = [],
        jpgArr = [];

    files.forEach(file => {
      let nama = file.name,
          mapped = nama.slice(9, nama.length);

      tempArr.push(mapped)
    });

    tempArr.shift();
    tempArr.forEach(file => {
      if (file.split('.')[1] == 'json') {
        jsonArr.push(file)
      } else {
        jpgArr.push(file)
      }
    })

    res.send(listToMatrix(jsonArr, jpgArr))
  })
  .catch(err => {
    console.error('ERROR:', err);
  });
}

Я использую Node.JS и собираюсь использовать Express для записи приведенного выше кода в REST API.

Ответы [ 2 ]

0 голосов
/ 23 марта 2019

Проверьте наличие обновленных метаданных в ответе и используйте это

const data = [{file:"a",metadata:{updated:"2019-03-23T17:42:53.846"}},{file:"b",metadata:{updated:"2017-03-23T17:42:53.846"}},{file:"c",metadata:{updated:"2016-03-23T17:42:53.846"}}];
//sorts ascending
let sortAsc = data.sort((a,b) => new Date(a.metadata.updated) - new Date(b.metadata.updated));
//sorts descending
let sortDesc = data.sort((a,b) => new Date(b.metadata.updated) - new Date(a.metadata.updated));
0 голосов
/ 21 марта 2019

Как насчет следующего:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Your Google Cloud Platform project ID
const projectId = 'YOUR PROJECT';

// Creates a client
const storage = new Storage({
  projectId: projectId,
});

// The name for the new bucket
const bucketName = 'YOUR-BUCKET';
const bucket = storage.bucket(bucketName);
bucket.getFiles(null, (err,data) => {
    data.sort((a, b) => {
        if (a.metadata.updated > b.metadata.updated) {
            return 1;
        }
        if (a.metadata.updated < b.metadata.updated) {
            return -1;
        }
        return 0;
    });
    for (file of data) {
        console.log(` ${file.metadata.name} - ${file.metadata.updated}`);
    }
});
...