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

fast-r2

v1.0.1

Published

A Node.js module to simplify Cloudflare R2 interactions, providing an instance-based API for uploads, deletions, and URL generation.

Readme

Cloudflare R2 Helper Module A lightweight Node.js module designed to simplify interactions with Cloudflare R2 storage, abstracting away the complexities of the S3-compatible API. This module provides convenient methods for uploading, deleting, and generating public URLs for files stored in your R2 buckets.

Features Instance-based API: Create a dedicated R2 client instance configured with your credentials.

Easy File Uploads: Streamlined method to upload Buffer data to R2, returning comprehensive details.

Simple File Deletion: Quickly remove files from your R2 bucket.

Public URL Generation: Generate direct public URLs for your R2 objects (if public access is configured).

Explicit Configuration: Pass R2 credentials directly during instance creation for clarity and security.

Robust Error Handling: Consistent error reporting for R2 operations.

Installation npm install your-r2-npm-module-name # Replace with your actual package name

or

yarn add your-r2-npm-module-name

Usage This module exports a single factory function, createR2, which you call to get an R2 client instance.

  1. Create an R2 Client Instance You must first create an instance of the R2 client by calling createR2 with an options object containing your Cloudflare R2 credentials and bucket details.

// Using CommonJS const createR2 = require('your-r2-npm-module-name');

// Using ES Modules (if your project supports it) // import createR2 from 'your-r2-npm-module-name';

// It's recommended to load sensitive credentials from environment variables // (e.g., using 'dotenv' package for local development) const CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID; const CLOUDFLARE_R2_ACCESS_KEY_ID = process.env.CLOUDFLARE_R2_ACCESS_KEY_ID; const CLOUDFLARE_R2_SECRET_ACCESS_KEY = process.env.CLOUDFLARE_R2_SECRET_ACCESS_KEY; const CLOUDFLARE_R2_BUCKET_NAME = process.env.CLOUDFLARE_R2_BUCKET_NAME; // The endpoint is optional, but good practice to define or derive const CLOUDFLARE_R2_ENDPOINT = process.env.CLOUDFLARE_R2_ENDPOINT || https://${CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com;

try { const r2 = createR2({ accountId: CLOUDFLARE_ACCOUNT_ID, accessKeyId: CLOUDFLARE_R2_ACCESS_KEY_ID, secretAccessKey: CLOUDFLARE_R2_SECRET_ACCESS_KEY, bucketName: CLOUDFLARE_R2_BUCKET_NAME, endpoint: CLOUDFLARE_R2_ENDPOINT // Optional });

// You can now use 'r2.uploadFile', 'r2.deleteFile', 'r2.getFileUrl'
// For example, in your backend service, you might export this 'r2' instance
// or functions that use it from a service layer (e.g., services/r2Service.js).
// module.exports = r2;

} catch (error) { console.error('Failed to initialize Cloudflare R2 client:', error.message); // Handle the error (e.g., exit application if critical, or throw further) process.exit(1); }

  1. Using the Client Methods Once you have an r2 client instance, you can call its methods:

r2.uploadFile(fileBuffer, fileName, contentType) Uploads a file to your R2 bucket.

fileBuffer: A Buffer containing the binary data of the file to upload.

fileName: A string representing the desired key (path and name) for the file in R2 (e.g., 'users/123/profile.jpg').

contentType: A string representing the MIME type of the file (e.g., 'image/jpeg', 'video/mp4').

Returns: A Promise that resolves to an object containing comprehensive information about the uploaded file, including: { Key, ETag, Bucket, Location (public URL), ContentType, Size }

Example:

// Assuming 'r2' instance has been created as shown above const fs = require('fs'); const path = require('path');

async function exampleUpload() { try { const filePath = path.join(__dirname, 'test-image.jpg'); // Replace with actual file path const fileBuffer = fs.readFileSync(filePath); const fileName = my-uploads/${Date.now()}-test-image.jpg; const contentType = 'image/jpeg';

    const uploadInfo = await r2.uploadFile(fileBuffer, fileName, contentType);
    console.log('File uploaded successfully:', uploadInfo);
    // You can store uploadInfo.Location (the public URL) in your database for later retrieval
} catch (error) {
    console.error('Error uploading file:', error.message);
}

}

// exampleUpload(); // Uncomment to run this example (ensure r2 instance is ready)

r2.deleteFile(fileName) Deletes a file from your R2 bucket.

fileName: A string representing the key (path and name) of the file to delete from R2.

Returns: A Promise that resolves upon successful deletion. Throws an error if deletion fails.

Example:

// Assuming 'r2' instance has been created async function exampleDelete() { try { const fileNameToDelete = 'my-uploads/1678888888888-test-image.jpg'; // Replace with actual file key await r2.deleteFile(fileNameToDelete); console.log(File '${fileNameToDelete}' deleted successfully from R2.); } catch (error) { console.error('Error deleting file:', error.message); } }

// exampleDelete(); // Uncomment to run this example

r2.getFileUrl(fileName) Generates the public URL for a file stored in your R2 bucket. This assumes your R2 bucket is configured for public access.

fileName: A string representing the key (path and name) of the file.

Returns: A string representing the public URL of the file.

Example:

// Assuming 'r2' instance has been created function exampleGetUrl() { const fileName = 'my-uploads/some-document.pdf'; // Replace with actual file key const publicUrl = r2.getFileUrl(fileName); console.log(Public URL for '${fileName}': ${publicUrl}); }

// exampleGetUrl(); // Uncomment to run this example

LICENSE This file contains the full text of the MIT License, which is a common and permissive open-source license.

MIT License

Copyright (c) 2025 Your Name [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.