AEM Cloud Service - NodeJS script to list assets in a folder or repository


Asset Reports can be used to list assets in a folder (subfolders), however for an offline way of doing it from outside AEM (or do some customized report generation eg. list images not videos) the following nodejs script might help...





1) Get the access token from Developer Console




2) In the following script list-all-assets-in-folder.js, set the value of AEM_TOKEN to access token generated above and run it using node eg. node list-all-assets-in-folder.js (used node -v = v19.0.1)

const https = require('https');
const fs = require('fs');

let log = "C:/dev/projects/temp/prod-my-assets.csv";
let AEM_HOST = 'author-p9999-e999999.adobeaemcloud.com';
let AEM_TOKEN = "eyJhbGciOi........";
let ROOT_FOLDER = "/content/dam/my-assets";
let totalCount = 0;
let goAhead = true;

requestFolderJson(ROOT_FOLDER);

function requestFolderJson(parentFolderPath) {
const options = {
hostname: AEM_HOST,
path: parentFolderPath + ".1.json",
headers: {
Authorization: 'Bearer ' + AEM_TOKEN
}
}

const INTERVAL = setInterval(() => {
if(goAhead){
clearInterval(INTERVAL);
doRequest(options, parentFolderPath);
}
}, 500);
}

function doRequest(options, parentFolderPath){
goAhead = false;

https.get(options,(res) => {
let body = "";

res.on("data", (chunk) => {
body += chunk;
});

res.on("end", () => {
try {
let json = JSON.parse(body);
let assetCountInFolder = 0, childPath;

Object.keys(json).forEach(function(name) {
childPath = parentFolderPath + "/" + name;

if(json[name]["jcr:primaryType"] == "sling:Folder"){
requestFolderJson(parentFolderPath + "/" + name)
}else if(json[name]["jcr:primaryType"] == "dam:Asset"){
assetCountInFolder++;
fs.appendFileSync(log, parentFolderPath + "/" + name + "\n");
}
});

totalCount += assetCountInFolder;

console.log(parentFolderPath + " = " + assetCountInFolder + ", total till now : " + totalCount);

goAhead = true;
} catch (error) {
console.error("ERROR : " + parentFolderPath + " : " + error.message);
goAhead = true;
}
});
}).on("error", (error) => {
console.error("CONN ERROR : " + parentFolderPath + " : " + error.message);
goAhead = true;
});
}

No comments:

Post a Comment