Skip to main content

File Operations SDK Methods

In this section, we will learn about all the available File Operations methods provided by the SDK.

Prerequisites

  1. Initialize the SDK before using wallet methods. See the Quick Start Guide for details.
  2. All methods require a wallet. Refer to createWallet for more information.
  3. All methods require a domain parameter, which is the network domain where your wallet and providers such as blobbers, sharders, miners, and validators are deployed. GoSDK will send requests to this domain.

File Operations Methods

The file operation methods allow you to perform various operations on files.

getLookupHash

Retrieves the lookup hash for a specific file path in an allocation. The lookup hash is used to uniquely identify a file in the allocation.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the allocation
allocationIdstringAllocation ID to check
filePathstringPath of the file in the allocation
walletActiveWalletActive Wallet details

Return Type

Promise<string>

Example

import { getLookupHash } from '@zerochain/sdk'

const lookupHash = await getLookupHash({
domain: 'mainnet.zus.network',
wallet: activeWallet
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
filePath: '/my-folder/my-file.txt',
})

createDir

Creates a directory on blobbers at the specified remote path.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the allocation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the directory will be created
remotePathstringThe remote path where the directory will be created

Example

import { createDir } from '@zerochain/sdk'

await createDir({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/new-directory'
})

setUploadMode

Sets the upload mode to modify the upload speed and CPU usage. The upload mode determines the trade-off between upload speed and resource consumption.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the upload
walletActiveWalletActive Wallet details
mode0 | 1 | 2Upload mode:
- 0: Low (slow uploads, consumes less CPU & memory)
- 1: Medium (default)
- 2: High (high-speed uploads, consumes more CPU & memory)
1

Example

import { setUploadMode } from '@zerochain/sdk'

await setUploadMode({
domain: 'mainnet.zus.network',
wallet: activeWallet,
mode: 2 // High speed uploads, but will consume more CPU & memory
})

multiUpload

Uploads multiple files in a batch. Files within a batch are uploaded in parallel. A single batch can handle up to 50 files at once. If you need to upload more than 50 files, the GoSDK will automatically create and manage multiple batches for you.

This method also supports resuming a paused upload. To resume, use the exact same bulkUploadOptions parameters that were initially used to start the upload. Only these original parameters should be provided when resuming the operation.

warning
  1. Always ensure you do not exceed the batch size limit of 50 files. This is strongly advised because, in an upcoming GoSDK versions, the methods like cancelUpload and pauseUpload will rely on the batchId of the 50-file batch to perform their operations.
  2. Only one batch upload can be in progress at a time.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the upload
walletActiveWalletActive Wallet details
bulkUploadOptionsBulkUploadOption[]Array of upload options for each file

BulkUploadOption Type

type BulkUploadOption = {
allocationId: string
webstreaming: boolean
isUpdate: boolean
isRepair: boolean
/** Number of blocks to upload per request */
numBlocks: number
file: File
remotePath: string
/** Whether to encrypt the file */
encrypt: boolean
thumbnailBytes: number[]
/** Callback function will be invoked with progress updates */
callback?: (
totalBytes: number,
completedBytes: number,
fileName: string,
blobURL: string,
error: string
) => void
}

Callback Parameters

NameTypeDescription
totalBytesnumberTotal bytes to upload
completedBytesnumberBytes uploaded so far
fileNamestringName of the file being uploaded
blobURLstringURL of the blobber being used for upload
errorstringError message, if any

Return Type

Promise<{ success?: boolean; error?: string }>

Example

import { multiUpload } from '@zerochain/sdk'

const result = await multiUpload({
domain: 'mainnet.zus.network',
wallet: activeWallet,
bulkUploadOptions: [
{
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
webstreaming: false,
isUpdate: false,
isRepair: false,
numBlocks: 100,
file: new File(['file content'], 'file1.txt'),
remotePath: '/my-folder/file1.txt',
encrypt: true,
thumbnailBytes: [],
callback: (totalBytes, completedBytes, fileName, blobURL, error) => {
console.log(`Upload progress for ${fileName}: ${completedBytes}/${totalBytes} bytes`);
if (error) {
console.error(`Error: ${error}`);
}
}
}
// Add more files here ...
]
})

if (result.success) {
console.log('Upload completed successfully');
} else {
console.error(`Upload failed: ${result.error}`);
}

pauseUpload

Pauses the upload operation of a file.

To resume the upload, call the multiUpload method with the same bulkUploadOptions parameter again.

Parameters

NameTypeDescriptionDefault value
walletActiveWalletActive Wallet details
domainNetworkDomainNetwork domain for the upload
allocationIdstringAllocation ID where the file is being uploaded
remotePathstringRemote path of the file to pause

Example

import { pauseUpload } from '@zerochain/sdk'

await pauseUpload({
wallet: activeWallet,
domain: 'mainnet.zus.network',
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt'
})

cancelUpload

Cancels the upload operation of a file.

Parameters

NameTypeDescriptionDefault value
walletActiveWalletActive Wallet details
domainNetworkDomainNetwork domain for the upload
allocationIdstringAllocation ID where the file is being uploaded
remotePathstringRemote path of the file to cancel

Example

import { cancelUpload } from '@zerochain/sdk'

await cancelUpload({
wallet: activeWallet,
domain: 'mainnet.zus.network',
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt'
})

getFileStats

Retrieves details for a file in an allocation.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the allocation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the file is located
remotePathstringRemote path of the file to retrieve details for

Return Type

Promise<FileStats[]>

Example

import { getFileStats } from '@zerochain/sdk'

const fileStats = await getFileStats({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt'
})

listObjects

Lists the files for a given allocation ID and remote path.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the allocation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID to list files from
remotePathstringRemote path of the directory to list
offsetnumberPagination offset for the list. Use 0 to turn off pagination.0
pageLimitnumberNumber of items per page. Use -1 to turn off pagination.-1

Return Type

Promise<ListResult>

Example

import { listObjects } from '@zerochain/sdk'

// list all files in a directory `/my-folder` without pagination
const listResult = await listObjects({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder',
})

getFileMetaByName

Retrieves file metadata by name (file search). This method allows you to search for files within an allocation by their name and optionally modify the returned file references.

Parameters

NameTypeDescriptionDefault value
walletActiveWalletActive Wallet details
domainNetworkDomainNetwork domain for the allocation
allocationIdstringAllocation ID to search within
fileNamestringName of the file to search for
modifyFileRef(file: FileRefByName) => TOptional function to modify the returned file references

Return Type

Promise<T[] | FileRefByName[]>

Example

import { getFileMetaByName } from '@zerochain/sdk'

const fileMetadata = await getFileMetaByName({
wallet: activeWallet,
domain: 'mainnet.zus.network',
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
fileName: 'file1.txt',
modifyFileRef: (file) => ({
...file,
customField: 'customValue' // Add custom fields if needed
})
})

multiDownload

Downloads multiple files in parallel in a batch. This method supports downloading files directly to disk (if supported by the browser) and provides progress updates via a callback function.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the download
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the files are located
authTicketstringRequired only for downloading shared files (non-owner)''
multiDownloadOptionsMultiDownloadOption[]Array of download options for each file
callback(totalBytes: number, completedBytes: number, fileName: string, blobURL: string, error?: string) => voidCallback function invoked with progress updates

MultiDownloadOption Type

type MultiDownloadOption = {
/** Remote path of the file to be downloaded */
remotePath: string
/** Local path where the file should be stored (optional) */
localPath?: string
/** Download operation type */
downloadType: 'file' | 'thumbnail'
/** Number of blocks to download per request */
numBlocks?: number
/** Required only for file download with an auth ticket */
remoteFileName: string
/** Lookup hash for remote file, required for auth ticket downloads */
remoteLookupHash?: string
/** Whether to download the file directly to disk (not supported on Safari) */
downloadToDisk: boolean
/** Suggested name for the file when downloading to disk (optional) */
suggestedName?: string
}

Callback Parameters

NameTypeDescription
totalBytesnumberTotal bytes to download
completedBytesnumberBytes downloaded so far
fileNamestringName of the file being downloaded
blobURLstringURL of the downloaded file
errorstringError message, if any

Return Type

Promise<DownloadCommandResponse[]>

DownloadCommandResponse Type

type DownloadCommandResponse = {
commandSuccess: boolean
error?: string
/** Name of the downloaded file */
fileName?: string
/** Blob URL of the downloaded file */
url?: string
}

Example

import { multiDownload } from '@zerochain/sdk'

const downloadResponses = await multiDownload({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
multiDownloadOptions: [
{
remotePath: '/my-folder/file1.txt',
downloadType: 'file',
numBlocks: 100,
remoteFileName: 'file1.txt',
downloadToDisk: true,
suggestedName: 'file1.txt'
}
// Add more download options as needed
],
callback: (totalBytes, completedBytes, fileName, blobURL, error) => {
console.log(`Download progress for ${fileName}: ${completedBytes}/${totalBytes} bytes`);
if (error) {
console.error(`Error: ${error}`);
}
}
})

downloadBlocks

Downloads a specified range of blocks from a file. This method is useful for downloading specific parts of a file, such as for resuming downloads or streaming.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the download
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the file is located
remotePathstringRemote path of the file to download
authTicketstringRequired only for downloading shared files (non-owner)''
lookupHashstringLookup hash of the file, used to locate the file if remotePath and allocationId are not provided
writeChunkFunc(lookupHash: string, chunk: Uint8Array, offset: number) => voidFunction to handle downloaded chunks
startBlocknumberStarting block number to download
endBlocknumberEnding block number to download

Return Type

Promise<Uint8Array>

Example

import { downloadBlocks } from '@zerochain/sdk'

const writeChunkFunc = (lookupHash: string, chunk: Uint8Array, offset: number) => {
console.log(`Received chunk for ${lookupHash} at offset ${offset}`);
// Handle the chunk (e.g., save to disk or process further)
}

const downloadedBlocks = await downloadBlocks({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt',
writeChunkFunc,
startBlock: 0,
endBlock: 10
})

console.log('Downloaded blocks:', downloadedBlocks);

cancelDownloadBlocks

Cancels the download of a specified range of blocks from a file. This method is used to stop an ongoing block download initiated by the downloadBlocks method.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the download
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID associated with the file
remotePathstringRemote path where the file is located
startnumberStart block number previously used in the downloadBlocks call
endnumberEnd block number previously used in the downloadBlocks call

Example

import { cancelDownloadBlocks } from '@zerochain/sdk'

await cancelDownloadBlocks({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt',
start: 0,
end: 10
})

downloadDirectory

Downloads files in a directory recursively. This method supports downloading all files/folders in a specified directory and provides progress updates via a callback function.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the download
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the directory is located
authTicketstringRequired only for downloading shared directories (non-owner)''
remotePathstringRemote path of the directory to download
callback(totalBytes: number, completedBytes: number, fileName: string, blobURL: string, error?: string) => voidCallback function invoked with progress updates

Callback Parameters

NameTypeDescription
totalBytesnumberTotal bytes to download
completedBytesnumberBytes downloaded so far
fileNamestringName of the file being downloaded
blobURLstringURL of the downloaded file
errorstringError message, if any

Example

import { downloadDirectory } from '@zerochain/sdk'

await downloadDirectory({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder',
callback: (totalBytes, completedBytes, fileName, blobURL, error) => {
console.log(`Download progress for ${fileName}: ${completedBytes}/${totalBytes} bytes`);
if (error) {
console.error(`Error: ${error}`);
}
}
})

cancelDownloadDirectory

Cancels the download of a directory initiated by downloadDirectory.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the download
walletActiveWalletActive Wallet details
remotePathstringRemote path of the directory to cancel

Example

import { cancelDownloadDirectory } from '@zerochain/sdk'

await cancelDownloadDirectory({
domain: 'mainnet.zus.network',
wallet: activeWallet,
remotePath: '/my-folder'
})

multiOperation

Performs multiple operations (copy, move, delete, create directory) together in a single batch.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the operations
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the operations will be performed
operationsMultiOperationOption[]Array of operations to perform

MultiOperationOption Type

type MultiOperationOption = {
/** Type of operation: 'copy', 'move', 'delete', or 'createdir' */
operationType: 'copy' | 'move' | 'delete' | 'createdir'
/** Remote path of the file/directory */
remotePath: string
/** Destination name (only for rename operation) */
destName?: string
/** Destination path (required for copy and move operations) */
destPath?: string
}

Example

import { multiOperation } from '@zerochain/sdk'

await multiOperation({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
operations: [
{
operationType: 'copy',
remotePath: '/my-folder/file1.txt',
destPath: '/my-folder/copy-file1.txt'
},
{
operationType: 'delete',
remotePath: '/my-folder/file2.txt'
},
{
operationType: 'createdir',
remotePath: '/my-folder/new-directory'
}
]
})

deleteFile

Deletes a file from an allocation. Only the owner of the allocation can delete a file.

note

To perform multiple deletions in a single call, use the multiOperation method instead.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the operation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the file is located
remotePathstringRemote path of the file to delete

Return Type

Promise<{ commandSuccess: boolean; error: string }>

Example

import { deleteFile } from '@zerochain/sdk'

const result = await deleteFile({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt'
})

if (result.commandSuccess) {
console.log('File deleted successfully');
} else {
console.error(`Error: ${result.error}`);
}

share

Generates an authTicket that provides authorization to the holder to access the specified file on the remote path. This method is used to share files with other users.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the operation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the file is located
remotePathstringRemote path of the file to be shared
clientIdstringClient ID / wallet ID of the recipient (for private sharing)""
encryptionPublicKeystringEncryption public key of the recipient (for private sharing)""
expirationnumberExpiration time of the auth ticket (in Unix timestamp seconds. e.g. 1647858200). Defaults to 0 (no expiration)0
revokebooleanWhether to revoke the share. (for private sharing)false
availableAfterstringTime after which the share becomes available. Possible formats:
1. Relative time with duration format (local timezone):
- +1h5m → Now + 1 hour 5 minutes
- +30s → Now + 30 seconds
- +2h → Now + 2 hours
2. Relative time with total seconds (local timezone):
- +3900 → Now + 3900 seconds (1 hour 5 minutes)
- +86400 → Now + 1 day (24 hours)
3. Unix timestamp (UTC-based):
- 1647858200 → Parses as a Unix timestamp
4. Absolute UTC datetime (YYYY-MM-DD HH:mm:ss):
- 2022-03-21 10:21:38 → Parses as March 21, 2022, 10:21:38 UTC
""

Return Type

Promise<string>

Example

import { share } from '@zerochain/sdk'

// Public share
const authTicket = await share({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt',
})

// Private share
await share({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
remotePath: '/my-folder/file1.txt',
clientId: recipientWalletId,
encryptionPublicKey: recipientEncryptionPublicKey,
})

listObjectsFromAuthTicket

Lists objects from an auth ticket. This method is useful for accessing a shared source by a non-owner.

Parameters

NameTypeDescriptionDefault value
domainNetworkDomainNetwork domain for the operation
walletActiveWalletActive Wallet details
allocationIdstringAllocation ID where the shared source is located
authTicketstringAuth ticket provided by a non-owner to access a shared source
lookupHashstringLookup hash for the file
offsetnumberPagination offset for the list. Use 0 to turn off pagination.0
pageLimitnumberNumber of items per page. Use -1 to turn off pagination.-1

Return Type

Promise<ListResult>

Example

import { listObjectsFromAuthTicket } from '@zerochain/sdk'

const listResult = await listObjectsFromAuthTicket({
domain: 'mainnet.zus.network',
wallet: activeWallet,
allocationId: '8695f8af52cdfc1e66d879407a5278703579d31de7ce0e2cf1707fdec9cc14c3',
authTicket: authTicketOfTheSharedFileOrFolder,
lookupHash: lookupHashOfTheSharedFileOrFolder,
})