LogoPear Docs
ReferencesBuilding blocks

Hyperdrive

Secure real-time distributed filesystem built on Hypercore-based storage.

stable

Hyperdrive stores filesystem metadata in a Hyperbee and file contents in a blob store, typically backed by one Corestore. Use this page for the instance surface; use the linked how-to guides for end-to-end replication flows.

For when to choose Hyperdrive over Hyperblobs or raw Hypercore, see From append-only logs to files.

Install

npm i hyperdrive

Quickstart

import Corestore from 'corestore'
import Hyperdrive from 'hyperdrive'

const store = new Corestore('./storage')
const drive = new Hyperdrive(store)

await drive.ready()

await drive.put('/hello.txt', Buffer.from('hello world'), {
  metadata: { type: 'text/plain' }
})

const buffer = await drive.get('/hello.txt')
const entry = await drive.entry('/hello.txt')

console.log(buffer.toString())
console.log(entry?.value.metadata)

await drive.close()

API Reference

Constructor and lifecycle

new Hyperdrive(store, [key])

src

Creates a new Hyperdrive instance. store must be an instance of Corestore.

ParameterTypeDefaultDescription
corestoreCorestore
keyBufferPublic key of an existing drive to load. May be omitted, passing opts in its place.
optsDriveOptions{}Drive options.
const Corestore = require('corestore')

const store = new Corestore('./storage')
const drive = new Hyperdrive(store)

await drive.ready()

Waits until internal state is loaded.

await drive.close()

Fully close this drive, including its underlying Hypercore backed datastructures.

await drive.purge()

src

Purge both cores (db and blobs) from your storage, completely removing all the drive's data.

  • Returns: Promise<void> — Resolves once both cores are purged from storage.
  • Throws: if called on a non-main session — only the main session can be purged.
await drive.purge()

Drive properties

drive.corestore

src

The Corestore instance used as storage.

drive.db

src

The underlying Hyperbee backing the drive file structure.

drive.core

src

The Hypercore used for drive.db.

drive.id

src

String containing the id (z-base-32 of the public key) identifying this drive.

  • Returns: string

drive.key

src

The public key of the Hypercore backing the drive.

drive.discoveryKey

src

The hash of the public key of the Hypercore backing the drive.

drive.contentKey

src

The public key of the Hyperblobs instance holding blobs associated with entries in the drive.

drive.writable

src

Boolean indicating if we can write or delete data in this drive.

  • Returns: boolean

drive.readable

src

Boolean indicating if we can read from this drive. After closing the drive this will be false.

  • Returns: boolean

drive.version

src

Number that indicates how many modifications were made, useful as a version identifier.

  • Returns: number

drive.supportsMetadata

src

Boolean indicating if the drive handles or not metadata. Always true.

  • Returns: boolean

Files

await drive.put(path, buffer, [options])

src

Creates a file at path in the drive. options are the same as in createWriteStream.

ParameterTypeDefaultDescription
pathstringPath to write the file at.
bufferBufferBlob contents to store.
optionsWriteOptions{}
  • Returns: Promise<void> — Resolves once the file has been written.
await drive.put('/blob.txt', Buffer.from('example'))

await drive.get(path, [options])

src

Reads the blob stored at path and resolves with its contents as a Buffer. Resolves with null when no blob exists at path, and also returns null for symbolic links.

ParameterTypeDescription
pathstringPath of the file to read.
optionsGetOptions
  • Returns: Promise<Buffer\|null> — The blob at path, or null if the path does not exist or is a symbolic link.
  • Throws: BLOCK_NOT_AVAILABLE if a required block is not available.

await drive.entry(path, [options])

src

Resolves with the entry stored at path, or null if no entry exists.

ParameterTypeDescription
pathstringPath of the entry to read.
optionsEntryOptions
  • Returns: Promise<object> — the entry at path in the drive.
  • Throws: if a symlink chain is recursive or exceeds 16 hops when follow is enabled.
OptionDefault
seqNumber
keyString
value

await drive.exists(path)

src

Checks whether an entry exists at path.

ParameterTypeDescription
pathstringPath to check.
  • Returns: Promise<boolean>true if the entry at path does exists, otherwise false.
const exists = await drive.exists('/blob.txt')

await drive.has(path)

src

Checks if path is saved to local store already.

ParameterTypeDescription
pathstringof the file or folder to check.
  • Returns: Promise<boolean>true if the blob (or every blob under a folder) is stored locally.
const exists = await drive.has('/blob.txt')

await drive.del(path)

src

Deletes the file at path from the drive.

ParameterTypeDescription
pathstringPath of the file to delete.
  • Returns: Promise<void> — Resolves once the entry has been deleted.
await drive.del('/blob.txt')

await drive.clear(path, [options])

src

Deletes the blob from storage to free up space, but the file structure reference is kept.

ParameterTypeDescription
pathstringPath of the file whose blob should be cleared.
optionsClearOptions
  • Returns: Promise<object> — A { blocks } object when diff is enabled, otherwise null.

await drive.clearAll([options])

src

Deletes all the blobs from storage to free up space, similar to how drive.clear() works.

ParameterType
optionsClearOptions
  • Returns: Promise<object> — A { blocks } object when diff is enabled, otherwise null.

await drive.symlink(path, linkname)

src

Creates an entry in drive at path that points to the entry at linkname.

ParameterTypeDefaultDescription
namestringPath of the symlink to create.
dststringPath the symlink points to.
optionsSymlinkOptions{}Symlink options.
  • Returns: Promise<void> — Resolves once the symlink entry has been created.
await drive.symlink('/images/logo.shortcut', '/images/logo.png')

drive.createReadStream(path, [options])

src

Returns a readable stream of the blob stored in the drive at path.

ParameterTypeDescription
pathstringPath of the file to read.
optionsobject
  • Returns: Readable — a stream to read out the blob stored in the drive at path.
OptionDefaultDescription
startNumberstart and end are inclusive
endNumber
lengthNumberlength overrides end, they're not meant to be used together
waittrueWait for blocks to be downloaded
timeout0Wait at max some milliseconds (0 means no timeout)

drive.createWriteStream(path, [options])

src

Stream a blob into the drive at path.

ParameterTypeDefaultDescription
pathstringPath of the file to write.
optionsWriteOptions{}Write options — the same as for drive.put(path, buffer, [options]).
  • Returns: Writable — A writable stream; data written is stored as the file's blob.

Directories and listings

drive.list(folder, [options])

src

Returns a stream of all entries in the drive at paths prefixed with folder.

ParameterTypeDefaultDescription
folderstringPath prefix to list. Defaults to the whole drive.
optionsobject{}
  • Returns: Readable — a stream of all entries in the drive at paths prefixed with folder.
OptionDefaultDescription
recursiveWhether to descend into all subfolders or not
ignoreIgnore files and folders by name
waittrueWait for block to be downloaded.

drive.readdir(folder, [options])

src

Returns a stream of the immediate subpaths of entries stored at paths prefixed by folder.

ParameterTypeDescription
folderstringPath prefix to read.
optionsobject
  • Returns: Readable — a stream of all subpaths of entries in drive stored at paths prefixed by folder.
OptionDefaultDescription
waittrueWait for block to be downloaded

await drive.entries([range], [options])

src

Returns a read stream of the drive entries within the given Hyperbee range.

ParameterTypeDescription
rangeobjectHyperbee range bounds (gt/gte/lt/lte).
optionsobjectoptions are the same as Hyperbee().createReadStream([range], [options]).
  • Returns: Readable — a read stream of entries in the drive.
for await (const entry of drive.entries()) console.log(entry.key)

drive.compare(entryA, entryB)

src

Compares two entries by their sequence number.

ParameterTypeDescription
entryAobjectThe first entry (as returned by drive.entry()).
entryBobjectThe second entry (as returned by drive.entry()).
  • Returns: number0 if entries are the same, 1 if entryA is newer, and -1 if entryB is newer.
const comparison = drive.compare(entryA, entryB)

drive.watch([folder])

src

Returns an async iterator that watches folder (defaults to /) and yields [current, previous] snapshot pairs whenever the drive changes. The snapshots are auto-closed before the next value, so do not close them yourself.

ParameterTypeDescription
folderstringto watch. Defaults to /.
  • Returns: Watcher — an iterator that listens on folder to yield changes, by default on /.
for await (const [current, previous] of watcher) {
  console.log(current.version)
  console.log(previous.version)
}

Versions and batched mutations

drive.batch()

src

Useful for atomically mutate the drive, has the same interface as Hyperdrive.

  • Returns: Hyperdrive — A batch with the same interface as Hyperdrive; call batch.flush() to commit.
const batch = drive.batch()
await batch.put('/a.txt', Buffer.from('a'))
await batch.flush()

await batch.flush()

src

Commit a batch of mutations to the underlying drive.

  • Returns: Promise<void> — Resolves once the batch is committed and closed.
await batch.flush()

drive.checkout(version)

src

Get a read-only snapshot of a previous version.

ParameterTypeDescription
versionnumberDrive version to snapshot.
  • Returns: Hyperdrive — A read-only Hyperdrive at the requested version.
const snapshot = drive.checkout(4)

drive.diff(version, folder, [options])

src

Efficiently create a stream of the changes to folder between version and drive.version.

ParameterTypeDescription
versionnumberDrive version to diff against the current drive.version.
folderstringPath prefix to scope the diff to. Omit for the whole drive.
optionsobjectDiff options, forwarded to the underlying Hyperbee diff stream.
  • Returns: Readable — A stream of { left, right } diff entries.
OptionDefaultDescription
leftObjectEntry in folder at drive.version for some path
rightObjectEntry in folder at drive.checkout(version) for some path

await drive.truncate(version, [options] })

src

Truncates the Hyperdrive to a previous version (both the file-structure reference and the blobs).

ParameterTypeDefaultDescription
versionnumberDrive version to truncate to.
optionsTruncateOptions{}Truncate options.
  • Returns: Promise<void> — Resolves once the drive and its blobs are truncated.
  • Throws: BAD_ARGUMENT if the truncation length is invalid.
await drive.truncate(drive.version - 1)

Replication, downloads, and blob access

drive.mirror(out, [options])

src

Efficiently mirror this drive into another. Returns a MirrorDrive instance constructed with options.

ParameterTypeDescription
outHyperdrive|LocaldriveDestination drive to mirror into.
optionsobjectMirror options, forwarded to MirrorDrive.
  • Returns: MirrorDrive — A MirrorDrive instance; await it or mirror.done() to finish.
const mirror = drive.mirror(out)
await mirror.done()

drive.download(folder, [options])

src

Downloads the blobs corresponding to all entries in the drive at paths prefixed with folder. Returns a Download object that resolves once all data has been downloaded:

ParameterTypeDefaultDescription
folderstring'/'Path prefix to download. Defaults to the whole drive.
optionsobjectoptions are the same as those for drive.list(folder, [options]).
  • Returns: Download — A Download object; await download.done() to know when complete.
const download = await drive.download(key)
await download.done()
download.destroy()

await drive.downloadDiff(version, folder, [options])

src

Downloads all the blobs in folder corresponding to entries in drive.checkout(version) that are not in drive.version. Returns a Download object that resolves once all data has been downloaded:

ParameterTypeDescription
versionnumberDrive version to diff against the current drive.version.
folderstringPath prefix to scope the download to. Omit for the whole drive.
optionsobjectDiff options, forwarded to drive.diff().
  • Returns: Download — A Download object; await download.done() to know when complete.
const download = await drive.downloadDiff(version, folder)
await download.done()
download.destroy()

await drive.downloadRange(dbRanges, blobRanges)

src

Downloads the entries and blobs stored in the ranges dbRanges and blobRanges. Returns a Download object that resolves once all data has been downloaded:

ParameterTypeDescription
dbRangesArray<object>Block ranges to download from the db (metadata) core.
blobRangesArray<object>Block ranges to download from the blobs core.
  • Returns: Download — A Download object; await download.done() to know when complete.
const download = await drive.downloadRange(dbRanges, blobRanges)
await download.done()
download.destroy()

drive.findingPeers()

src

Indicate to Hyperdrive that you're finding peers in the background, requests will be on hold until this is done.

  • Returns: Function — A done callback to call once peer discovery has finished.
const done = drive.findingPeers()
swarm.flush().then(done, done)

drive.replicate(isInitiatorOrStream)

src

Creates a replication stream for the drive. Pass true/false to create a new stream as initiator/responder, or pass an existing stream or socket to replicate over it. See corestore.replicate for how replication works.

ParameterTypeDescription
isInitiatorboolean|Streamtrue/false to initiate replication, or an existing stream/socket to replicate over.
optsobjectReplication options, forwarded to corestore.replicate().
  • Returns: Stream — A replication stream.
const swarm = new Hyperswarm()
const done = drive.findingPeers()
swarm.on('connection', (socket) => drive.replicate(socket))
swarm.join(drive.discoveryKey)
swarm.flush().then(done, done)

await drive.update([options])

src

Waits for initial proof of the new drive version until all findingPeers are done.

ParameterType
optionsUpdateOptions
  • Returns: Promise<boolean>true if the drive advanced to a new version, otherwise false.

await drive.getBlobs()

src

Returns the Hyperblobs instance storing the blobs indexed by drive entries.

await drive.put('/file.txt', Buffer.from('hi'))

const buffer1 = await drive.get('/file.txt')

const blobs = await drive.getBlobs()
const entry = await drive.entry('/file.txt')
const buffer2 = await blobs.get(entry.value.blob)

// => buffer1 and buffer2 are equals

await drive.getBlobsLength(checkout)

src

Returns the length of the Hyperblobs instance at the time of the specified Hyperdrive version (defaults to the current version).

ParameterTypeDescription
checkoutnumberDrive version to measure. Defaults to the current version.
  • Returns: Promise<number> — the length of the Hyperblobs instance at the time of the specified Hyperdrive version (defaults to the current version).
const blobsLength = await drive.getBlobsLength()

Types

DriveOptions

Options for creating a Hyperdrive.

PropertyTypeDefaultDescription
encryptionKeyBufferEncryption key used to encrypt and decrypt the underlying cores.
onwaitFunctionHook called when a block has to be downloaded before it can be read.
activebooleantrueWhether the drive's cores actively maintain peer connections.

TruncateOptions

Options for drive.truncate().

PropertyTypeDefaultDescription
blobsnumberCorresponding blobs length, if known. Recommended to let the method figure it out.

UpdateOptions

Options for drive.update().

PropertyTypeDefaultDescription
waitbooleanfalseWhether to wait for peers before resolving. Use this or drive.findingPeers() to make await drive.update() blocking.

GetOptions

Options for drive.get().

PropertyTypeDefaultDescription
waitbooleantrueWait for the block to be downloaded.
timeoutnumber0Max milliseconds to wait (0 means no timeout).

WriteOptions

Options for writing a file (drive.put() and drive.createWriteStream()).

PropertyTypeDefaultDescription
executablebooleanfalseWhether the blob at the path is an executable.
metadata*nullExtended file information, i.e. an arbitrary JSON value.
dedupbooleanfalseReuse the existing blob if the content is unchanged (createWriteStream only).

ClearOptions

Options for clearing blobs (drive.clear() and drive.clearAll()).

PropertyTypeDefaultDescription
diffbooleanfalseWhen enabled, returns a { blocks } object reporting the blocks cleared; otherwise the result is null.

SymlinkOptions

Options for drive.symlink().

PropertyTypeDefaultDescription
metadata*nullExtended file information, i.e. an arbitrary JSON value.

EntryOptions

Options for drive.entry().

PropertyTypeDefaultDescription
followbooleanfalseFollow symlinks, up to 16 deep or it throws an error.
waitbooleantrueWait for the block to be downloaded.
timeoutnumber0Max milliseconds to wait (0 means no timeout).

Errors

Coded errors this module can throw — catch them via err.code.

ErrorThrown when
BAD_ARGUMENTif the truncation length is invalid.
BLOCK_NOT_AVAILABLEif a required block is not available.

See also

On this page