Download
Downloads and optionally decrypts files from Filecoin.
Signature
async download(pieceCid: string, options?: DownloadOptions): Promise<DownloadResult>Description
The download function retrieves files from Filecoin using their piece CID and automatically decrypts them if you have the proper permissions. For private files, you need to own the access NFT. Public files can be decrypted by anyone.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
pieceCid | string | Yes | Filecoin piece CID of the file to download |
options | DownloadOptions | No | Download configuration options |
DownloadOptions
interface DownloadOptions {
outputPath?: string; // Local file path to save
decrypt?: boolean; // Attempt decryption (default: true)
onProgress?: (progress: DownloadProgress) => void;
}DownloadProgress
interface DownloadProgress {
message: string;
bytesDownloaded?: number;
totalBytes?: number;
percentage?: number;
}Returns
Promise<DownloadResult> - A Promise that resolves to an object with the following properties:
| Property | Type | Description |
|---|---|---|
data | Uint8Array | Downloaded file data |
fileSize | number | File size in bytes |
decrypted | boolean | Whether file was successfully decrypted |
metadata | object | File metadata including name, upload info |
Examples
Basic Download
import { Synapse } from '@filoz/synapse-sdk';
import { SynapseStorageSDK } from '@keypo/synapse-storage-sdk';
import { ethers } from 'ethers';
// Initialize SDK (same as upload)
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
const provider = new ethers.JsonRpcProvider('https://api.calibration.node.glif.io/rpc/v1');
const signer = wallet.connect(provider);
const synapse = await Synapse.create({
signer,
withCDN: true,
});
const sdk = new SynapseStorageSDK(synapse, {
network: 'calibration',
rpcUrl: 'https://api.calibration.node.glif.io/rpc/v1',
encryption: {
registryAddress: '0x8370eE1a51B5F31cc10E2f4d786Ff20198B10BBE',
validationAddress: '0x35ADB6b999AbcD5C9CdF2262c7190C7b96ABcE4C',
bundlerRpcUrl: 'https://rpc.zerodev.app/api/v3/YOUR_PROJECT_ID/chain/84532'
}
}, process.env.PRIVATE_KEY);
// Download file
const pieceCid = 'bafk2bzacedt7j7lnpxvzfdks7ooqvzf2lgjklhkh...';
const result = await sdk.download(pieceCid, {
onProgress: (progress) => {
console.log(progress.message);
}
});
console.log('Download successful!');
console.log('File size:', result.fileSize, 'bytes');
console.log('Decrypted:', result.decrypted);
console.log('Content:', new TextDecoder().decode(result.data));Download and Save File
import { writeFileSync } from 'fs';
const result = await sdk.download(pieceCid, {
decrypt: true,
onProgress: (progress) => {
console.log(`${progress.message}`);
if (progress.bytesDownloaded && progress.totalBytes) {
const percent = (progress.bytesDownloaded / progress.totalBytes * 100).toFixed(1);
console.log(`Progress: ${percent}%`);
}
}
});
// Save to local file
const filename = `downloaded-${Date.now()}.txt`;
writeFileSync(filename, result.data);
console.log(`Saved to: ${filename}`);
// Display metadata
if (result.metadata) {
console.log('Metadata:', JSON.stringify(result.metadata, null, 2));
}Download Multiple Files
async function downloadFiles(pieceCids) {
const results = [];
for (const cid of pieceCids) {
try {
console.log(`Downloading ${cid}...`);
const result = await sdk.download(cid, {
onProgress: (progress) => console.log(` ${progress.message}`)
});
results.push({
success: true,
cid,
fileSize: result.fileSize,
decrypted: result.decrypted
});
} catch (error) {
console.error(`Failed to download ${cid}:`, error.message);
results.push({ success: false, cid, error: error.message });
}
}
return results;
}
// Usage
const cids = ['bafk...', 'bafk...', 'bafk...'];
const results = await downloadFiles(cids);
console.log(`Downloaded ${results.filter(r => r.success).length} of ${cids.length} files`);Access Control
- Public files: Anyone can decrypt these files
- Private files: Only NFT holders can decrypt
- Permission errors: If you don’t have access, you’ll get an NFT/permission error
Notes
- Use the piece CID returned from
sdk.upload()to download files - Public files can be decrypted by anyone
- Private files require NFT ownership for decryption
- Progress tracking shows download and decryption status
- Files are automatically decrypted if you have permissions
See Also
- Upload - Upload and encrypt files
- List - List your uploaded files
- Share - Share private files with other wallets
- Configuration - SDK configuration options