Data Types

Bytescale JavaScript SDK (Node.js)

Lightweight headless SDK for uploading, processing, and hosting files with Bytescale.

Install

To install via NPM:

npm install @bytescale/sdk node-fetch

Note: this SDK depends on the Fetch API (a polyfill is included above).

Upload a File Basic Example

To upload a file with the Bytescale JavaScript SDK for Node.js (basic example):

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const uploadManager = new Bytescale.UploadManager({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "free" // Get API key: https://www.bytescale.com/get-started
7});
8
9uploadManager
10 .upload({
11 // Supported types:
12 // - String
13 // - Blob
14 // - ArrayBuffer
15 // - Buffer
16 // - ReadableStream (Node.js), e.g. fs.createReadStream("file.txt")
17 data: "Hello World",
18
19 // Required if 'data' is a stream, buffer, or string.
20 mime: "text/plain",
21
22 // Required if 'data' is a stream, buffer, or string.
23 originalFileName: "my_file.txt",
24
25 // Required if 'data' is a stream.
26 // size: 5098, // e.g. fs.statSync("file.txt").size
27 })
28 .then(
29 ({ fileUrl, filePath }) => {
30
31 // --------------------------------------------
32 // File successfully uploaded!
33 // --------------------------------------------
34 // The 'filePath' uniquely identifies the file,
35 // and is what you should save to your DB.
36 // --------------------------------------------
37 console.log(`File uploaded to: ${fileUrl}`);
38
39 },
40 error => console.error(`Error: ${error.message}`, error)
41 );

See also: UploadManagerParams

Upload a File Advanced Example

To upload a file with the Bytescale JavaScript SDK for Node.js (advanced example):

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const uploadManager = new Bytescale.UploadManager({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "free" // Get API key: https://www.bytescale.com/get-started
7});
8
9uploadManager
10 .upload({
11
12 // Supported types:
13 // - String
14 // - Blob
15 // - ArrayBuffer
16 // - Buffer
17 // - ReadableStream (Node.js), e.g. fs.createReadStream("file.txt")
18 data: "Hello World",
19
20 // ---------
21 // Optional:
22 // ---------
23
24 // Required if 'data' is a stream.
25 // size: 5098, // e.g. fs.statSync("file.txt").size
26
27 // Required if 'data' is a stream, buffer, or string.
28 mime: "text/plain",
29
30 // Required if 'data' is a stream, buffer, or string.
31 originalFileName: "my_file.txt",
32
33 // Reports progress: bytesTotal, bytesSent, progress.
34 // onProgress: ({ progress }) => console.log(progress),
35
36 // Controls multipart upload concurrency. Ignored if 'data' is a stream.
37 // maxConcurrentUploadParts: 4,
38
39 // Up to 2KB of arbitrary JSON.
40 // metadata: {
41 // productId: 60891
42 // },
43
44 // Up to 25 tags per file.
45 // tags: [
46 // "example_tag"
47 // ],
48
49 // About file paths:
50 // - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
51 // - You can override the API key's file upload path by specifying a path below.
52 // - You may use path variables (e.g. "{UTC_DAY}"): https://www.bytescale.com/docs/path-variables
53 // path: {
54 // folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
55 // fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
56 // },
57
58 // Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
59 // cancellationToken: {
60 // isCancelled: false
61 // }
62 })
63 .then(
64 ({ fileUrl, filePath }) => {
65
66 // --------------------------------------------
67 // File successfully uploaded!
68 // --------------------------------------------
69 // The 'filePath' uniquely identifies the file,
70 // and is what you should save to your DB.
71 // --------------------------------------------
72 console.log(`File uploaded to: ${fileUrl}`);
73
74 },
75 error => console.error(`Error: ${error.message}`, error)
76 );

See also: UploadManagerParams and Path Variables

Download a File

To download a file from your Bytescale account:

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const fileApi = new Bytescale.FileApi({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
7});
8
9fileApi
10 .downloadFile({
11 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
12 filePath: "/uploads/2022/12/25/hello_world.txt"
13 })
14 .then(response => response.text()) // .text() | .json() | .blob() | .stream()
15 .then(
16 fileContents => console.log(fileContents),
17 error => console.error(error)
18 );

To learn more about these parameters, see the DownloadFile operation »

To get a file's URL (instead of downloading the file as a binary stream) use the UrlBuilder »

Delete a File

To delete an uploaded file:

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const fileApi = new Bytescale.FileApi({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
7});
8
9fileApi
10 .deleteFile({
11 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
12 filePath: "/uploads/2022/12/25/image.jpg"
13 })
14 .then(
15 () => console.log("File deleted."),
16 error => console.error(error)
17 );

There are no additional parameters to pass to the DeleteFile operation.

List Files

To list the children of a folder:

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const folderApi = new Bytescale.FolderApi({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
7});
8
9folderApi
10 .listFolder({
11 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
12 folderPath: "/",
13 recursive: false
14 })
15 .then(
16 // Note: operation is paginated, see 'result.cursor' and 'params.cursor'.
17 result => console.log(`Items in folder: ${result.items.length}`),
18 error => console.error(error)
19 );

To learn more about these parameters, see the ListFolder operation »

Get File Metadata

To get the full details of a file (including any custom metadata):

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3
4const fileApi = new Bytescale.FileApi({
5 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
6 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
7});
8
9fileApi
10 .getFileDetails({
11 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
12 filePath: "/uploads/2022/12/25/image.jpg"
13 })
14 .then(
15 fileDetails => console.log(fileDetails), // includes: size, mime, metadata, etc.
16 error => console.error(error)
17 );

There are no additional parameters to pass to the GetFileDetails operation.

Transforming Files

You can transform uploaded files using Bytescale's File Processing APIs:

To transform files with code and receive the result as a binary stream in JavaScript, use the processFile method:

1import * as Bytescale from "@bytescale/sdk";
2import nodeFetch from "node-fetch";
3import fs from "fs";
4
5const fileApi = new Bytescale.FileApi({
6 fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
7 apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
8});
9
10fileApi
11 .processFile({
12 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
13 filePath: "/uploads/2022/12/25/image.jpg",
14
15 // Transformation Presets vs File Processing APIs:
16 // - To use a preset:
17 // - Specify the preset name below (e.g. "thumbnail").
18 // - Exclude the "transformationParams" field.
19 // - Presets are created in the Bytescale Dashboard.
20 // - To use a File Processing API:
21 // - Specify the File Processing API below (e.g. "image", "video", "audio", etc).
22 // - Include the "transformationParams" field.
23 // - Parameters are documented here: https://www.bytescale.com/docs/file-processing-apis
24 transformation: "image",
25
26 // Array Support:
27 // - Certain File Processing APIs, such as the Archive Processing API, have transformation
28 // parameters that can be specified multiple times (e.g. the "file" parameter).
29 // - To do this, use multiple objects to specify the same parameter name multiple times.
30 transformationParams: [
31 {
32 w: 800,
33 h: 600,
34 fit: "crop"
35 }
36 ]
37 })
38 .then(response => response.stream()) // .text() | .json() | .blob() | .stream()
39 .then(
40 imageByteStream =>
41 new Promise((resolve, reject) => {
42 const writer = fs.createWriteStream("image-thumbnail.jpg");
43 writer.on("close", resolve);
44 writer.on("error", reject);
45 imageByteStream.pipe(writer);
46 })
47 )
48 .then(
49 () => console.log("Thumbnail saved to 'image-thumbnail.jpg'"),
50 error => console.error(error)
51 );

To transform files via the URL, use the UrlBuilder to construct file transformation URLs (see below).

File transformation URLs can be used in your webpages, e.g. in the src attribute of <img> and <video> elements.

Building URLs

After uploading a file, you should save its filePath to your DB instead of its fileUrl, and use the UrlBuilder to lazily create URLs:

  • filePath values are shorter.

  • filePath values allow you to change the domain in the future (e.g. if you move to a custom CNAME).

  • filePath values allow you to select different file transformations at runtime (e.g. /raw/, /image/, etc.).

You can use the UrlBuilder to create URLs from filePath values:

Raw Files

Using the UrlBuilder to get raw file URLs (i.e. URLs to original files):

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/raw/example.jpg"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.jpg"
});

You can upload any file type to Bytescale. Use /raw/ when downloading files that don't need to be transformed.

Transformation Presets

Using the UrlBuilder to transform files using transformation presets:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/thumbnail/example.jpg"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.jpg",
options: {
transformation: "preset",
transformationPreset: "thumbnail"
}
});

Transformation presets are created in the Bytescale Dashboard.

Images

Using the UrlBuilder to transform images using the Image Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process images with:
// ↪ https://upcdn.io/abc1234/image/example.jpg?w=800&h=600
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.jpg",
options: {
transformation: "image",
transformationParams: {
"w": 800,
"h": 600
}
}
});

See the Image Processing API for the full list of transformationParams when transformation: "image".

Videos

Using the UrlBuilder to transform videos using the Video Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process videos with:
// ↪ https://upcdn.io/abc1234/video/example.mov?f=mp4-h264&h=1080
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.mov",
options: {
transformation: "video",
transformationParams: {
"f": "mp4-h264",
"h": 1080
}
}
});

See the Video Processing API for the full list of transformationParams when transformation: "video".

Audio

Using the UrlBuilder to transform audio using the Audio Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process audio with:
// ↪ https://upcdn.io/abc1234/audio/example.wav?f=aac&br=192
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.wav",
options: {
transformation: "audio",
transformationParams: {
"f": "aac",
"br": 192
}
}
});

See the Audio Processing API for the full list of transformationParams when transformation: "audio".

Archives

Using the UrlBuilder to extract the file document.docx from the uploaded ZIP file example.zip:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.zip",
options: {
transformation: "archive",
transformationParams: {
m: "extract"
},
artifact: "/document.docx"
}
});

See the Archive Processing API for the full list of transformationParams when transformation: "archive".

Antivirus

Using the UrlBuilder to scan files for viruses, trojans, and other malware:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/antivirus/example.zip"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.zip",
options: {
transformation: "antivirus"
}
});

See the Antivirus API for full details about the JSON response structure.

Authentication

The Bytescale JavaScript SDK requires a Bytescale API key, and optionally a JWT:

API keys

You must always provide a valid apiKey to the Bytescale JavaScript SDK.

With API key auth, the requester has access to the resources configured in the API key's permissions.

  • Secret API keys: can perform all API operations (see the Bytescale JavaScript SDK).

  • Public API keys: can perform file uploads and file downloads only. File overwrites, file deletes, and all other destructive operations cannot be performed using public API keys.

You must always use public API keys (e.g. public_***) in your client-side code.

JWTs (Optional)

When using public API keys you can optionally pass a JWT to extend the requester's permissions beyond that of the API key. In addition, you can configure your API key to make it reject requests that aren't accompanied by a valid JWT. This prevents users from taking your API key and using it outside of your application.

JWTs are issued by your application and are verified by Bytescale using a public key certificate.

To use JWTs, please use the Bytescale JavaScript SDK AuthManager »

UploadManager

Use the UploadManager to upload files, strings, BLOBs, buffers, and streams to Bytescale.

upload

Uploads a file, string, BLOB, buffer, or stream as the data parameter. (size is only required if the data is a stream.)

Signature

function upload(params: UploadManagerParams): Promise<FileDetails>

Parameters

See details: UploadManagerParams

Result

{
"accountId": String,
"etag": String | Null,
"filePath": String,
"fileUrl": String,
"lastModified": Integer,
"mime": String,
"originalFileName": String | Null,
"size": Integer,
"tags": String[]
}

See details: FileDetails

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadManager = new Bytescale.UploadManager({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadManager
.upload({
"data": "Hello World"
})
.then(
result => console.log(result),
error => console.error(error)
);

AuthManager

Use the AuthManager to authenticate browser requests to the Bytescale API and Bytescale CDN using JWTs.

For server-side requests, we recommend using secret API keys instead of JWTs. If you prefer to use JWTs but are not running your code in the browser, such as in a desktop application, you will need to handle JWTs manually according to the authentication docs »

Instructions:

  1. Create a JWT endpoint.

  2. Call AuthManager.beginAuthSession in your client-side code (see instructions below).

  3. The Bytescale SDK will authenticate all subsequent requests to the Bytescale API and CDN using JWTs.

To learn more about private files, authentication, and JWTs, please see: Authentication »

beginAuthSession

Begins a JWT auth session with the Bytescale API and Bytescale CDN.

You must first create a JWT endpoint in your backend API.

After calling this method, the Bytescale SDK will periodically acquire a JWT from your backend API, which then be used to authenticate subsequent requests to the Bytescale API and CDN from the browser.

You can only call this method if isAuthSessionActive() === false else an error will be returned.

You should call this method after the user has signed into your web app.

After calling this method:

  1. You must await the returned promise before attempting to perform any downloads or API operations that require authentication.

    isAuthSessionActive() will return true immediately after beginAuthSession() is called (but before the promise resolves).

    isAuthSessionReady() will return true only after the promise succeeds, so can also be used to check for auth readiness.

  2. You can then use private file URLs in src elements in img/video/audio elements, etc.

You can only call this method in the browser. For server-side requests, we recommend using secret API keys instead of JWTs. If you prefer to use JWTs but are not running your code in the browser, such as in a desktop application, you will need to handle JWTs manually according to the authentication docs »

Signature

function beginAuthSession(params: BeginAuthSessionParams): Promise<void>

Parameters

See details: BeginAuthSessionParams

Example

import * as Bytescale from "@bytescale/sdk";
async function onSignIn() {
// The URL for your auth API endpoint.
// - For help implementing your auth API endpoint, see: https://www.bytescale.com/docs/auth/generating-jwts
// Your URL must:
// - Return a JWT as plain text.
// - Return a 'content-type: text/plain' response header.
// - Return a 200 status code.
// - Return a signed JWT (i.e. the JWT must include 2x "." characters) using RS256.
// - The public key certificate must be added to the Bytescale Dashboard.
// - The JWT must not be wrapped with "".
const authUrl = "https://your-web-app/your-auth-url";
// Headers required by your auth API endpoint (e.g. 'authorization' header).
const authHeaders = () => Promise.resolve({
authorization: "some auth token"
});
// Wait for authentication to complete:
await Bytescale.AuthManager.beginAuthSession({
accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
authUrl,
authHeaders,
// Optional:
// - To support modern browsers that block third-party cookies (like Safari),
// you should consider enabling service workers by uncommenting the below.
// - Before uncommenting, you must implement the "/bytescale-auth-sw.js" script.
// - See: https://www.bytescale.com/docs/types/BeginAuthSessionParams#serviceWorkerScript
// serviceWorkerScript: "/bytescale-auth-sw.js"
});
}
// Call this after your user signs in:
await onSignIn();
// After the 'onSignIn' promise completes:
// - You can start referencing private files in <img> elements, etc.
// - You can start performing other operations permitted by the JWT in your client-side code.
// (e.g. file deletions, file uploads to specific folders, etc.)

endAuthSession

Ends a JWT auth session with the Bytescale API and Bytescale CDN.

Signature

function endAuthSession(): Promise<void>

Parameters

This method takes no parameters.

isAuthSessionActive

Checks if an authenticated Bytescale API and Bytescale CDN session is active.

This is true immediately after the beginAuthSession() method is called.

Check this flag before attempting to call beginAuthSession(): beginAuthSession() will fail if isAuthSessionActive() === true.

Signature

function isAuthSessionActive(): boolean

Parameters

This method takes no parameters.

Result

Returns a boolean value.

isAuthSessionReady

Checks if an authenticated Bytescale API and Bytescale CDN session is active and ready to authenticate HTTP requests.

This is true only after the beginAuthSession() promise succeeds (i.e. when private files are ready to be loaded).

Check this flag before attempting to load private files (e.g. when rendering <img> elements that reference private files).

Signature

function isAuthSessionReady(): boolean

Parameters

This method takes no parameters.

Result

Returns a boolean value.

UploadApi

Client methods for the Upload API.

Use the UploadManager instead of calling these methods directly.

uploadFromUrl

Upload from a URL with a single HTTP request:

Signature

function uploadFromUrl(params: UploadFromUrlParams): Promise<BasicUploadResponse>

Parameters

See details: UploadFromUrlParams

Result

{
"accountId": String,
"etag": String,
"filePath": String,
"fileUrl": String
}

See details: BasicUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadApi = new Bytescale.UploadApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.uploadFromUrl({
"accountId": "YOUR_ACCOUNT_ID",
"uploadFromUrlRequest": {
"url": "https://assets.bytescale.com/example.jpg"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

beginMultipartUpload

Begins a new multipart file upload process.

Signature

function beginMultipartUpload(params: BeginMultipartUploadParams): Promise<BeginMultipartUploadResponse>

Parameters

See details: BeginMultipartUploadParams

Result

See details: BeginMultipartUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadApi = new Bytescale.UploadApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.beginMultipartUpload({
"accountId": "YOUR_ACCOUNT_ID",
"beginMultipartUploadRequest": {
"size": 43182
}
})
.then(
result => console.log(result),
error => console.error(error)
);

completeUploadPart

Marks an upload part as uploaded.

You must call this endpoint after you have successfully issued a PUT request to the uploadUrl on the corresponding UploadPart.

Signature

function completeUploadPart(params: CompleteUploadPartParams): Promise<CompleteMultipartUploadResponse>

Parameters

See details: CompleteUploadPartParams

Result

Arbitrary JSON Object

See details: CompleteMultipartUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadApi = new Bytescale.UploadApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.completeUploadPart({
"accountId": "YOUR_ACCOUNT_ID",
"completeUploadPartRequest": {
"etag": "33a64df551425fcc55e4d42a148795d9f25f89d4"
},
"uploadId": "Kd759aLFxttm69kZ",
"uploadPartIndex": 7
})
.then(
result => console.log(result),
error => console.error(error)
);

getUploadPart

Gets a remaining upload part for a multipart file upload.

Signature

function getUploadPart(params: GetUploadPartParams): Promise<UploadPart>

Parameters

{
"accountId": String,
"uploadId": String,
}

See details: GetUploadPartParams

Result

See details: UploadPart

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadApi = new Bytescale.UploadApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.getUploadPart({
"accountId": "YOUR_ACCOUNT_ID",
"uploadId": "Kd759aLFxttm69kZ",
"uploadPartIndex": 7
})
.then(
result => console.log(result),
error => console.error(error)
);

listUploadParts

Lists the remaining upload parts for a multipart file upload.

An empty array is returned when the upload is complete.

Signature

function listUploadParts(params: ListUploadPartsParams): Promise<UploadPartList>

Parameters

{
"accountId": String,
"uploadId": String
}

See details: ListUploadPartsParams

Result

See details: UploadPartList

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const uploadApi = new Bytescale.UploadApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.listUploadParts({
"accountId": "YOUR_ACCOUNT_ID",
"uploadId": "Kd759aLFxttm69kZ"
})
.then(
result => console.log(result),
error => console.error(error)
);

FileApi

Client methods for the File API.

downloadFile

Downloads a file in its original/unprocessed state.

Signature

function downloadFile(params: DownloadFileParams): Promise<BinaryResult>

Parameters

{
"accountId": String,
"cache": Boolean,
"cache_ttl": Number,
"cache_ttl_404": Number,
"filePath": String,
"version": String
}

See details: DownloadFileParams

Result

{
"blob": Function,
"json": Function,
"stream": Function,
"text": Function
}

See details: BinaryResult

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.downloadFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

processFile

Processes a file and returns the result.

Signature

function processFile(params: ProcessFileParams): Promise<BinaryResult>

Parameters

{
"accountId": String,
"artifact": String,
"cache": Boolean,
"cache_only": Boolean,
"cache_perm": String,
"cache_ttl": Number,
"cache_ttl_404": Number,
"filePath": String,
"version": String
}

See details: ProcessFileParams

Result

{
"blob": Function,
"json": Function,
"stream": Function,
"text": Function
}

See details: BinaryResult

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.processFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg",
"transformation": "image",
"transformationParams": [
{
"w": 800,
"h": 600,
"fit": "crop"
}
]
})
.then(
result => console.log(result),
error => console.error(error)
);

processFileAndSave

Processes a file and saves the result.

Signature

function processFileAndSave(params: ProcessFileAndSaveParams): Promise<ProcessFileAndSaveResponse>

Parameters

See details: ProcessFileAndSaveParams

Result

Arbitrary JSON Object

See details: ProcessFileAndSaveResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.processFileAndSave({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/source/image.jpg",
"processFileAndSaveRequest": {
"destination": "/destination/image.jpg"
},
"transformation": "image",
"transformationParams": [
{
"w": 800,
"h": 600,
"fit": "crop"
}
]
})
.then(
result => console.log(result),
error => console.error(error)
);

getFileDetails

Gets the full details (e.g. metadata, tags, etc.) for a file.

Signature

function getFileDetails(params: GetFileDetailsParams): Promise<FileDetails>

Parameters

{
"accountId": String,
"filePath": String
}

See details: GetFileDetailsParams

Result

{
"accountId": String,
"etag": String | Null,
"filePath": String,
"fileUrl": String,
"lastModified": Integer,
"mime": String,
"originalFileName": String | Null,
"size": Integer,
"tags": String[]
}

See details: FileDetails

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.getFileDetails({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFile

Copies a file synchronously.

Signature

function copyFile(params: CopyFileParams): Promise<CopyFileResponse>

Parameters

See details: CopyFileParams

Result

{
"status": String
}

See details: CopyFileResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.copyFile({
"accountId": "YOUR_ACCOUNT_ID",
"copyFileRequest": {
"destination": "/destination/file.txt",
"source": "/source/file.txt"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFileBatch

Copies multiple files asynchronously.

Signature

function copyFileBatch(params: CopyFileBatchParams): Promise<AsyncResponse>

Parameters

See details: CopyFileBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.copyFileBatch({
"accountId": "YOUR_ACCOUNT_ID",
"copyFileBatchRequest": {
"files": [
{
"destination": "/destination/file.txt",
"source": "/source/file.txt"
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFile

Deletes a file synchronously.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFile(params: DeleteFileParams): Promise<void>

Parameters

{
"accountId": String,
"filePath": String
}

See details: DeleteFileParams

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.deleteFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFileBatch

Deletes multiple files asynchronously.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFileBatch(params: DeleteFileBatchParams): Promise<AsyncResponse>

Parameters

See details: DeleteFileBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const fileApi = new Bytescale.FileApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.deleteFileBatch({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFileBatchRequest": {
"files": [
"/uploads/image.jpg"
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

FolderApi

Client methods for the Folder API.

putFolder

Creates or updates the folder specified by the folderPath.

If the folder's ancestors do not exist, they will be created automatically (with empty FolderSettings).

Note: you don't need to create folders before uploading files to them.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function putFolder(params: PutFolderParams): Promise<FolderDetails>

Parameters

See details: PutFolderParams

Result

See details: FolderDetails

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.putFolder({
"accountId": "YOUR_ACCOUNT_ID",
"putFolderRequest": {
"folderPath": "/uploads"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

getFolderDetails

Gets the full details (e.g. permission, storage layer, etc.) for a folder.

Returns an empty object if no settings have been configured for this folder.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function getFolderDetails(params: GetFolderDetailsParams): Promise<FolderDetails>

Parameters

{
"accountId": String,
"folderPath": String
}

See details: GetFolderDetailsParams

Result

See details: FolderDetails

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.getFolderDetails({
"accountId": "YOUR_ACCOUNT_ID",
"folderPath": "/uploads"
})
.then(
result => console.log(result),
error => console.error(error)
);

listFolder

Lists the folder's contents.

The result may be paginated: subsequent pages can be requested by passing the cursor from the response into the next request.

Pagination is complete when the response includes isPaginationComplete=true.

Signature

function listFolder(params: ListFolderParams): Promise<ListFolderResponse>

Parameters

{
"accountId": String,
"cursor": String,
"dryRun": Boolean,
"folderPath": String,
"includeFiles": Boolean,
"limit": Integer,
"recursive": Boolean
}

See details: ListFolderParams

Result

See details: ListFolderResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.listFolder({
"accountId": "YOUR_ACCOUNT_ID",
"folderPath": "/uploads"
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFolder

Copies a folder asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

Signature

function copyFolder(params: CopyFolderParams): Promise<AsyncResponse>

Parameters

See details: CopyFolderParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.copyFolder({
"accountId": "YOUR_ACCOUNT_ID",
"copyFolderRequest": {
"destination": "/destination/folder",
"source": "/source/folder",
"recursive": true
}
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFolderBatch

Copies multiple folders asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

Signature

function copyFolderBatch(params: CopyFolderBatchParams): Promise<AsyncResponse>

Parameters

See details: CopyFolderBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.copyFolderBatch({
"accountId": "YOUR_ACCOUNT_ID",
"copyFolderBatchRequest": {
"folders": [
{
"destination": "/destination/folder",
"source": "/source/folder",
"recursive": true
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFolder

Deletes a folder asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

External storage: external files are only deleted when you directly delete a file or subfolder of a folder that has external storage configured. If you delete the folder itself, only the mapping is removed.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFolder(params: DeleteFolderParams): Promise<AsyncResponse>

Parameters

See details: DeleteFolderParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.deleteFolder({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFolderRequest": {
"folderPath": "/uploads"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFolderBatch

Deletes multiple folders asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

External storage: external files are only deleted when you directly delete a file or subfolder of a folder that has external storage configured. If you delete the folder itself, only the mapping is removed.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFolderBatch(params: DeleteFolderBatchParams): Promise<AsyncResponse>

Parameters

See details: DeleteFolderBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const folderApi = new Bytescale.FolderApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.deleteFolderBatch({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFolderBatchRequest": {
"folders": [
{
"folderPath": "/uploads"
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

JobApi

Client methods for the Job API.

getJob

Gets information on a background job.

Requires a secret_* API key.

Signature

function getJob(params: GetJobParams): Promise<JobSummary>

Parameters

{
"accountId": String,
"jobId": String,
"jobType": String
}

See details: GetJobParams

Result

{
"accountId": String,
"created": Integer,
"code": String,
"details": Object,
"message": String
},
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String,
"lastUpdated": Integer,
"status": String,
}

See details: JobSummary

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const jobApi = new Bytescale.JobApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.getJob({
"accountId": "YOUR_ACCOUNT_ID",
"jobId": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"jobType": "AntivirusJob"
})
.then(
result => console.log(result),
error => console.error(error)
);

listRecentJobs

Lists the 10 most recently created jobs for the specified job type(s).

Requires a secret_* API key.

Signature

function listRecentJobs(params: ListRecentJobsParams): Promise<ListRecentJobsResponse>

Parameters

{
"accountId": String,
"jobType": String[]
}

See details: ListRecentJobsParams

Result

See details: ListRecentJobsResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const jobApi = new Bytescale.JobApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.listRecentJobs({
"accountId": "YOUR_ACCOUNT_ID",
"jobType": [
"AntivirusJob"
]
})
.then(
result => console.log(result),
error => console.error(error)
);

cancelJob

Cancels an in-progress background job.

Requires a secret_* API key.

Signature

function cancelJob(params: CancelJobParams): Promise<void>

Parameters

{
"accountId": String,
"jobId": String,
"jobType": String
}

See details: CancelJobParams

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const jobApi = new Bytescale.JobApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.cancelJob({
"accountId": "YOUR_ACCOUNT_ID",
"jobId": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"jobType": "AntivirusJob"
})
.then(
result => console.log(result),
error => console.error(error)
);

CacheApi

Client methods for the Cache API.

resetCache

Resets the Bytescale CDN cache for a specific path, path prefix, or for your entire account.

You can choose to reset the edge cache, or permanent cache, or both caches.

Warning: Resetting the permanent cache (by setting resetPermanentCache: true) may lead to a significant increase in processing time if numerous file transformations need to be re-performed upon their next request.

Recommended: Prevent cache resets by adding a ?v=<etag> querystring parameter to your URLs. This ensures your URLs change when your files change, eliminating the need for cache resets. The etag field is returned by GetFileDetails and all upload operations, and can be saved to your database.

Example patterns:

"/*"

"/raw/example.jpg"

"/image/example.jpg"

"/image/customers/abc/*"

You may only use * at the end of the pattern. You must not include your account ID prefix in the pattern.

Signature

function resetCache(params: ResetCacheParams): Promise<AsyncResponse>

Parameters

See details: ResetCacheParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
import nodeFetch from "node-fetch";
const cacheApi = new Bytescale.CacheApi({
fetchApi: nodeFetch, // import nodeFetch from "node-fetch"; // Only required for Node.js. TypeScript: 'nodeFetch as any' may be necessary.
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
cacheApi
.resetCache({
"accountId": "YOUR_ACCOUNT_ID",
"resetCacheRequest": {
"pattern": "/raw/example.jpg",
"resetEdgeCache": true,
"resetPermanentCache": true
}
})
.then(
result => console.log(result),
error => console.error(error)
);

Was this section helpful? Yes No

You are using an outdated browser.

This website requires a modern web browser -- the latest versions of these browsers are supported: