Search code examples
javascriptaemsightly

AEM: Access JS File in DAM using JavaScript Use-API


I have a certain JS File in DAM, that contains a JSON. I would like to access that file in the helper JS using any methods of JavaScript USE API in Sightly. I know it can be done using Java quite easily, but I would like to do it in a manner that I do not want to touch any Java Code.

I tried things like below. But after that, an input stream is unavailable to convert it to a stream data.

request.resourceResolver.getResource("/path/to/dam/file.js");

AND

request.resourceResolver.getResource("/path/to/dam/file.js").adaptTo(com.adobe.granite.asset.api.Asset);

Solution

  • I saw the answer posted just now. But I had used another similar method before I saw this.

    Here is it. It is very similar to the answer but with a few extra steps.

    asset = request.resourceResolver.getResource(jsonPath).adaptTo(com.day.cq.dam.api.Asset);
    rend = asset.getOriginal().adaptTo(com.day.cq.dam.api.Rendition);
    

    OR DIRECTLY

    rend= request.resourceResolver.getResource(jsonPath+"/jcr:content/renditions/original").adaptTo(com.day.cq.dam.api.Rendition);
    

    AND THEN

    inputStream = rend.adaptTo(java.io.InputStream);
    var is;
    var c = '';
    var flag = false;
    try {
    // reads till the end of the stream
    while ((is = inputStream.read()) != -1) {
          c = c + String.fromCharCode(is);
    }
    
     } catch (e) {
       // if any I/O error occurs
       log.debug("Input Stream Error " + e)
     }