Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
@bytescale/sdk
Advanced tools
Bytescale is the developer platform for images, video, and audio.
Use the Bytescale JavaScript SDK to upload, transform, and serve files at scale.
Full SDK Documentation • Upload Widget • Media Processing APIs • Storage • CDN
npm install @bytescale/sdk node-fetch
npm install @bytescale/sdk
Or:
<script src="https://js.bytescale.com/sdk/v3"></script>
This library is isomorphic, which means you can upload files from Node.js, or the browser, or both.
import * as Bytescale from "@bytescale/sdk";
import fetch from "node-fetch";
const uploadManager = new Bytescale.UploadManager({
fetchApi: fetch, // or 'fetch as any' (please note: you must use 'node-fetch' as errors can occur with other implementations)
apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
});
uploadManager
.upload({
// ---------
// Required:
// ---------
// Your account ID (e.g. "W142hJk")
accountId: "YOUR_ACCOUNT_ID",
// Supported types for 'data' field:
// - String
// - Buffer
// - ReadableStream (Node.js), e.g. fs.createReadStream("file.txt")
data: "Hello World",
// ---------
// Optional:
// ---------
// Required if 'data' is a stream.
// size: 5098, // e.g. fs.statSync("file.txt").size
// Required if 'data' is a stream, buffer, or string.
mime: "text/plain",
// Required if 'data' is a stream, buffer, or string.
originalFileName: "my_file.txt"
// Controls multipart upload concurrency. Ignored if 'data' is a stream.
// maxConcurrentUploadParts: 4,
// Up to 2KB of arbitrary JSON.
// metadata: {
// productId: 60891
// },
// Up to 25 tags per file.
// tags: [
// "example_tag"
// ],
// About file paths:
// - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
// - You can override the API key's file upload path by specifying a path below.
// - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables
// path: {
// folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
// fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
// },
// Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
// cancellationToken: {
// isCancelled: false
// }
})
.then(
({ fileUrl, filePath }) => {
// --------------------------------------------
// File successfully uploaded!
// --------------------------------------------
// The 'filePath' uniquely identifies the file,
// and is what you should save to your DB.
// --------------------------------------------
console.log(`File uploaded to: ${fileUrl}`);
},
error => console.error(`Error: ${error.message}`, error)
);
<html>
<head>
<script src="https://js.bytescale.com/sdk/v3"></script>
<script>
// import * as Bytescale from "@bytescale/sdk"
const uploadManager = new Bytescale.UploadManager({
apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
});
const onFileSelected = async event => {
const file = event.target.files[0];
try {
const { fileUrl, filePath } = await uploadManager.upload({
// ---------
// Required:
// ---------
// Your account ID (e.g. "W142hJk")
accountId: "YOUR_ACCOUNT_ID",
// Supported types for 'data' field:
// - String
// - Blob
// - File (i.e. from a DOM file input element)
data: file
// ---------
// Optional:
// ---------
// Required if 'data' is a stream. (Not required for DOM file inputs, blobs, buffers, or strings.)
// size: 5098, // e.g. fs.statSync("file.txt").size
// Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
// mime: "application/octet-stream",
// Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
// originalFileName: "my_file.txt",
// Controls multipart upload concurrency. Ignored if 'data' is a stream.
// maxConcurrentUploadParts: 4,
// Up to 2KB of arbitrary JSON.
// metadata: {
// productId: 60891
// },
// Up to 25 tags per file.
// tags: [
// "example_tag"
// ],
// About file paths:
// - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
// - You can override the API key's file upload path by specifying a path below.
// - You may use path variables (e.g. "{UTC_DAY}"): http://localhost:3201/docs/path-variables
// path: {
// folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
// fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
// },
// Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
// cancellationToken: {
// isCancelled: false
// }
});
// --------------------------------------------
// File successfully uploaded!
// --------------------------------------------
// The 'filePath' uniquely identifies the file,
// and is what you should save to your API.
// --------------------------------------------
alert(`File uploaded:\n${fileUrl}`);
} catch (e) {
alert(`Error:\n${e.message}`);
}
};
</script>
</head>
<body>
<input type="file" onchange="onFileSelected(event)" />
</body>
</html>
import * as Bytescale from "@bytescale/sdk";
import fetch from "node-fetch"; // Only required for Node.js
const fileApi = new Bytescale.FileApi({
fetchApi: fetch, // 'fetch as any' for TypeScript
apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.downloadFile({
accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
filePath: "/uploads/2022/12/25/hello_world.txt"
})
.then(response => response.text()) // .text() | .json() | .blob() | .stream()
.then(
fileContents => console.log(fileContents),
error => console.error(error)
);
Use the UrlBuilder
to get a URL to your file (if you need a URL instead of downloading the file).
import * as Bytescale from "@bytescale/sdk";
import fetch from "node-fetch"; // Only required for Node.js
const fileApi = new Bytescale.FileApi({
fetchApi: fetch, // 'fetch as any' for TypeScript
apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.processFile({
accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
filePath: "/uploads/2022/12/25/image.jpg",
// See: https://www.bytescale.com/docs/image-processing-api
transformation: "image",
transformationParams: {
w: 800,
h: 600
}
})
.then(response => response.stream()) // .text() | .json() | .blob() | .stream()
.then(
imageByteStream =>
new Promise((resolve, reject) => {
const writer = fs.createWriteStream("image-thumbnail.jpg");
writer.on("close", resolve);
writer.on("error", reject);
imageByteStream.pipe(writer);
})
)
.then(
() => console.log("Thumbnail saved to 'image-thumbnail.jpg'"),
error => console.error(error)
);
Use the UrlBuilder
to get a URL to your file (if you need a URL instead of downloading the file).
import * as Bytescale from "@bytescale/sdk";
import fetch from "node-fetch"; // Only required for Node.js
const fileApi = new Bytescale.FileApi({
fetchApi: fetch, // 'fetch as any' for TypeScript
apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.getFileDetails({
accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
filePath: "/uploads/2022/12/25/image.jpg"
})
.then(
fileDetails => console.log(fileDetails),
error => console.error(error)
);
import * as Bytescale from "@bytescale/sdk";
import fetch from "node-fetch"; // Only required for Node.js
const folderApi = new Bytescale.FolderApi({
fetchApi: fetch, // 'fetch as any' for TypeScript
apiKey: "YOUR_BYTESCALE_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.listFolder({
accountId: "YOUR_UPLOAD_ACCOUNT_ID", // e.g. "W142hJk"
folderPath: "/",
recursive: false
})
.then(
// Note: operation is paginated, see 'result.cursor' and 'params.cursor'.
result => console.log(`Items in folder: ${result.items.length}`),
error => console.error(error)
);
The Bytescale JavaScript SDK supports two types of authorization:
The Bytescale JavaScript SDK automatically adds the apiKey
from the constructor to the Authorization
header for all requests made via the SDK.
With API key auth, the requester has access to the resources available to the API key:
Secret API keys (secret_***
) have access to all API endpoints.
Public API keys (public_***
) have access to file upload, file download, and file listing API endpoints. (File listing is disabled by default. This can be changed in the API key's settings.)
Each Public API Key and Secret API Key can have its read/write access limited to a subset of files/folders.
JWT cookies are optional.
With JWT cookies, the user can download private files directly via URL, as authorization is performed implicitly via a session cookie. This allows the browser to display private files in <img>
and <video>
elements.
With JWT cookies, the user can also perform API requests (e.g. file uploads) granted by the JWT's payload. This is because the Bytescale JavaScript SDK automatically injects the user's JWT into the authorization-token
request header for all API requests, assuming the AuthManager.beginAuthSession
method has been called.
Note: when using JWT cookies to download files, the ?auth=true
query parameter must be added to the URL.
Learn more about using JWT cookies »
Use the UrlBuilder
to make URLs for your uploaded files:
import { UrlBuilder } from "@bytescale/sdk";
To get the URL for the uploaded image /example.jpg
in its original form, use the following params:
// Returns: "https://upcdn.io/1234abc/raw/example.jpg"
new UrlBuilder().url({
accountId: "1234abc",
filePath: "/example.jpg"
});
To resize the uploaded image /example.jpg
to 800x600, use the following params:
// Returns: "https://upcdn.io/1234abc/image/example.jpg?w=800&h=600"
new UrlBuilder().url({
accountId: "1234abc",
filePath: "/example.jpg",
options: {
transformation: "image",
transformationParams: {
w: 800,
h: 600
}
}
});
To transcode the uploaded video /example.mov
to MP4/H.264 in HD, use the following params:
// Returns: "https://upcdn.io/1234abc/video/example.mov?f=mp4-h264&h=1080"
new UrlBuilder().url({
accountId: "1234abc",
filePath: "/example.mov",
options: {
transformation: "video",
transformationParams: {
f: "mp4-h264",
h: 1080
}
}
});
To transcode the uploaded audio /example.wav
to AAC in 192kbps, use the following params:
// Returns: "https://upcdn.io/1234abc/audio/example.wav?f=aac&br=192"
new UrlBuilder().url({
accountId: "1234abc",
filePath: "/example.wav",
options: {
transformation: "audio",
transformationParams: {
f: "aac",
br: 192
}
}
});
To extract the file document.docx
from the uploaded ZIP file /example.zip
, use the following params:
// Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx"
new UrlBuilder().url({
accountId: "1234abc",
filePath: "/example.zip",
options: {
transformation: "archive",
transformationParams: {
m: "extract"
},
artifact: "/document.docx"
}
});
Bytescale is the best way to serve images, videos, and audio for web apps.
Bytescale supports AWS S3, Cloudflare R2, Google Storage, DigitalOcean Spaces, and Bytescale Storage.
Bytescale JavaScript SDK Docs »
FAQs
Bytescale JavaScript SDK
The npm package @bytescale/sdk receives a total of 11,873 weekly downloads. As such, @bytescale/sdk popularity was classified as popular.
We found that @bytescale/sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.