Skip to main content

Assets SDK

The Assets SDK helps you read the contents of Assets Items in your code. In this article, you will learn how to read the contents of Assets Items by interacting with the Assets Element using the Assets SDK.

Definition

class MyAssets extends Iterable<File> {
readonly [path: string]: File | null
keys(): Iterator<string>
values(): Iterator<File>
entries(): Iterator<[string, File]>
}

Usage

If you want to use the Assets SDK in your Babel app, you first need to add an Assets Element and give it an appropriate name. You can then import the Assets SDK dependencies with that name inside Element:

import { myAssets } from "#elements";

// Properties
const resourceFile = myAssets[resourceName];
console.log(`Content-Type is ${resourceFile.type}`);
console.log(`Content-Length is ${resourceFile.size}`);
console.log(`fileName is ${resourceFile.name}`);
console.log(`item keys are ${Object.keys(myAssets)}`);

// Ways to Looping through the Assets
for (let file of myAssets) { console.log(file.name, file.lastModified, file.type) }
for (let [path, file] of myAssets.entries()) { console.log(path, file.name, file.lastModified) }
for (let path of myAssets.keys()) { console.log(`path is ${path}`) }
for (let file of myAssets.values()) { console.log(`file is ${file.name}`) }

// Ways to read the Assets Item
await resourceFile.text()
await resourceFile.arrayBuffer()
for await (let chunk of resourceFile.stream()) { console.log(chunk) }
resourceFile.stream().getReader().read()
resourceFile.stream().getReader({mode: 'byob'}).read(view)

Examples

Return an HTML page

import * as Koa from "koa";
import { myAssets } from "#elements";
export default async function (request: Koa.Request, response: Koa.Response, ctx: Koa.Context) {
const assetsItem = myAssets["/index.html"]
response.type = "text/html"
return assetsItem.text();
}

Access the HTTP Element to download the Assets Item

import * as Koa from "koa";
import { myAssets } from "#elements";
export default async function (request: Koa.Request, response: Koa.Response, ctx: Koa.Context) {
const fileName = request.query['assets'] as string;
const assetsItem = myAssets[fileName]
response.type = assetsItem!.type
response.set('Content-Disposition', `attachment; filename=${assetsItem.name}`);
return assetsItem.text();
}