Skip to content

Instantly share code, notes, and snippets.

@aedm
Created October 2, 2024 16:17
Show Gist options
  • Save aedm/612f2afc5569fae0b37552fb282076ce to your computer and use it in GitHub Desktop.
Save aedm/612f2afc5569fae0b37552fb282076ce to your computer and use it in GitHub Desktop.
Upload a file to Backblaze B2 and copy the URL to clipboard using Deno 2
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { writeText } from "https://deno.land/x/copy_paste/mod.ts";
import { basename } from "https://deno.land/[email protected]/path/mod.ts";
import B2 from 'npm:backblaze-b2';
// Read file name from command line arguments
const args = parse(Deno.args);
if (args._.length !== 1) {
console.error("Please provide a file path as an argument.");
Deno.exit(1);
}
const filePath = args._[0] as string;
// Read Backblaze B2 credentials from environment variables
const B2_KEY_ID = Deno.env.get("B2_KEY_ID");
const B2_APPLICATION_KEY = Deno.env.get("B2_APPLICATION_KEY");
const B2_BUCKET_NAME = Deno.env.get("B2_BUCKET_NAME");
if (!B2_KEY_ID || !B2_APPLICATION_KEY || !B2_BUCKET_NAME) {
console.error("Please set B2_ACCOUNT_ID, B2_APPLICATION_KEY, and B2_BUCKET_NAME environment variables.");
Deno.exit(1);
}
// Authenticate with Backblaze B2
const b2 = new B2({
applicationKeyId: B2_KEY_ID,
applicationKey: B2_APPLICATION_KEY,
});
await b2.authorize();
// Get bucket id
let bucketResponse = await b2.getBucket({ bucketName: B2_BUCKET_NAME });
const bucketId = bucketResponse.data.buckets[0].bucketId;
// Read file
const fileName = basename(filePath);
const fileContent = await Deno.readFile(filePath);
// Upload file
console.log("Uploading file to Backblaze B2...");
const response = await b2.getUploadUrl({ bucketId });
const x = await b2.uploadFile({
uploadUrl: response.data.uploadUrl,
uploadAuthToken: response.data.authorizationToken,
fileName,
data: fileContent,
});
// Construct a direct download link to the file and paste it to the clipboard
const fileUrl = `https://f001.backblazeb2.com/file/${B2_BUCKET_NAME}/${fileName}`
await writeText(fileUrl);
console.log("URL copied to clipboard:", fileUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment