npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

storage-bucket-js

v1.0.0

Published

A comprehensive JavaScript/TypeScript library for storage bucket operations with API key authentication. Supports upload, download, list, and delete operations with CORS handling.

Readme

Storage Bucket JS

A comprehensive JavaScript/TypeScript library for storage bucket operations with API key authentication. Supports upload, download, list, and delete operations with CORS handling for web applications.

Features

  • 🚀 Easy to Use: Simple and intuitive API
  • 📁 File Operations: Upload, download, list, and delete files
  • 🔐 Secure Authentication: API key-based authentication
  • 📊 Progress Tracking: Upload and download progress callbacks
  • 🌐 CORS Support: Built-in CORS handling for web applications
  • 📱 Cross-Platform: Works in Node.js and browsers
  • 📋 Pagination: Built-in pagination for file listings
  • 🔍 Search & Filter: Search files and filter by MIME type
  • 💪 TypeScript: Full TypeScript support with type definitions
  • ⚡ Modern: Built with modern JavaScript/TypeScript

Installation

npm install storage-bucket-js

Quick Start

import { StorageBucketClient, ApiCredentials } from 'storage-bucket-js';

// Create credentials
const credentials = new ApiCredentials(
  'sk_your_api_key_here',
  'your_api_secret_here',
  'https://your-storage-bucket-domain.com'
);

// Create client
const client = new StorageBucketClient(credentials);

// Test connection
try {
  await client.testConnection();
  console.log('Connected to storage bucket!');
} catch (error) {
  console.error('Connection failed:', error.message);
}

Usage Examples

File Upload

// Upload from File object (browser)
const fileInput = document.getElementById('file-input') as HTMLInputElement;
const file = fileInput.files[0];

try {
  const result = await client.uploadFile(1, file, (loaded, total) => {
    const progress = (loaded / total) * 100;
    console.log(`Upload progress: ${progress.toFixed(2)}%`);
  });
  
  console.log('Upload successful:', result.file);
} catch (error) {
  console.error('Upload failed:', error.message);
}

// Upload from buffer
const buffer = new Uint8Array([/* your file data */]);
const result = await client.uploadFileFromBuffer(
  1, 
  'document.pdf', 
  buffer, 
  'application/pdf'
);

File Download

// Download file as ArrayBuffer
const fileId = 123;
const buffer = await client.downloadFile(fileId, (loaded, total) => {
  console.log(`Download progress: ${(loaded / total) * 100}%`);
});

// Download and save to device (browser)
await client.downloadFileToDevice(fileId, 'my-file.pdf');

List Files

// List files with pagination
const response = await client.listFiles(1, {
  page: 1,
  limit: 20,
  search: 'document',
  mimeType: 'application/pdf',
  sortBy: 'date',
  sortOrder: 'desc'
});

console.log('Files:', response.files);
console.log('Pagination:', response.pagination);

// Iterate through all files
for (const file of response.files) {
  console.log(`${file.fileName} (${file.fileSizeFormatted})`);
  console.log(`Type: ${file.fileType}, Uploaded: ${file.uploadDate}`);
}

File Management

// Get file information
const fileInfo = await client.getFileInfo(123);
console.log('File details:', fileInfo);

// Delete file
const deleteResult = await client.deleteFile(123);
if (deleteResult.success) {
  console.log('File deleted successfully');
}

Error Handling

import { StorageBucketException } from 'storage-bucket-js';

try {
  await client.uploadFile(1, file);
} catch (error) {
  if (error instanceof StorageBucketException) {
    switch (error.statusCode) {
      case 401:
        console.error('Invalid API credentials');
        break;
      case 403:
        console.error('Access denied');
        break;
      case 404:
        console.error('File not found');
        break;
      case 429:
        console.error('Rate limit exceeded');
        break;
      default:
        console.error('Storage error:', error.message);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

API Reference

StorageBucketClient

The main client class for interacting with the storage bucket API.

Constructor

new StorageBucketClient(credentials: ApiCredentials)

Methods

  • testConnection(): Promise<boolean> - Test connection to the API server
  • uploadFile(bucketId: number, file: File, onProgress?: ProgressCallback): Promise<UploadResponse> - Upload a file
  • uploadFileFromBuffer(bucketId: number, fileName: string, buffer: ArrayBuffer | Uint8Array, mimeType?: string, onProgress?: ProgressCallback): Promise<UploadResponse> - Upload from buffer
  • downloadFile(fileId: number, onProgress?: ProgressCallback): Promise<ArrayBuffer> - Download file as buffer
  • downloadFileToDevice(fileId: number, fileName?: string, onProgress?: ProgressCallback): Promise<void> - Download and save to device
  • listFiles(bucketId: number, options?: ListFilesOptions): Promise<FilesListResponse> - List files with filtering
  • deleteFile(fileId: number): Promise<DeleteResponse> - Delete a file
  • getFileInfo(fileId: number): Promise<BucketFile> - Get file information

ApiCredentials

new ApiCredentials(apiKey: string, apiSecret: string, baseUrl: string)
  • apiKey - Your API key (must start with 'sk_')
  • apiSecret - Your API secret
  • baseUrl - The base URL of your storage bucket API

BucketFile

Represents a file in the storage bucket with metadata and utility methods.

Properties:

  • id: number - File ID
  • fileName: string - File name
  • fileSize: number - File size in bytes
  • fileSizeFormatted: string - Human-readable file size
  • mimeType: string - MIME type
  • uploadDate: Date - Upload timestamp
  • downloadUrl: string - Download URL
  • fileExtension: string - File extension
  • fileType: string - File type category (image, video, audio, document, other)
  • isImage: boolean - True if file is an image
  • isVideo: boolean - True if file is a video
  • isAudio: boolean - True if file is an audio file
  • isDocument: boolean - True if file is a document

FileUtils

Utility class for file operations:

  • getFileName(filePath: string): string - Extract filename from path
  • getFileExtension(fileName: string): string - Get file extension
  • getMimeType(fileName: string): string | null - Get MIME type from filename
  • sanitizeFileName(fileName: string): string - Remove invalid characters from filename
  • formatFileSize(bytes: number): string - Format file size in human-readable format
  • isImage(mimeType: string): boolean - Check if MIME type is an image
  • isVideo(mimeType: string): boolean - Check if MIME type is a video
  • isAudio(mimeType: string): boolean - Check if MIME type is an audio file
  • isDocument(mimeType: string): boolean - Check if MIME type is a document
  • fileToArrayBuffer(file: File): Promise<ArrayBuffer> - Convert File to ArrayBuffer
  • downloadBlob(blob: Blob, fileName: string): void - Trigger browser download

CORS Configuration

For web applications, you need to configure CORS on your storage bucket server. See the CORS Setup Guide for detailed instructions.

Environment Support

  • Node.js: 16.0.0 or higher
  • Browsers: Modern browsers with ES2020 support
  • TypeScript: 4.0 or higher

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Support

Changelog

See CHANGELOG.md for version history and changes.