Alexander Praetorius
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Prerequisites This is for people familiar or eager to learn JavaScript. If you don't know JavaScript yet, maybe work through https://javascript.info first and search for nodejs crashcourse tutorials. You need to have https://nodejs.org/en installed On windows `nvs` https://github.com/jasongin/nvs can be recommended to do that, on other operating systems `nvm` does a good job doing so https://github.com/nvm-sh/nvm Once that is done, install the p2p pear runtime with `npm install -g pear` and continue with the actual tutorial below. # Introduction to progrmaming Peer to Peer Filesystems **Hyperdrive** is a secure, real-time distributed file system designed for easy peer-to-peer file sharing. In the same way that a Hyperbee is just a wrapper around a Hypercore, a Hyperdrive is a wrapper around two Hypercores: one is a Hyperbee index for storing file metadata, and the other is used to store file contents. This How-to consists of three applications: `drive-writer-app`, `drive-reader-app` and `bee-reader-app`. Now let's mirror a local directory into a Hyperdrive, replicate it with a reader peer, who then mirrors it into their own local copy. When the writer modifies its drive, by adding, removing, or changing files, the reader's local copy will be updated to reflect that. To do this, we'll use two additional tools: **MirrorDrive** and **LocalDrive**, which handle all interactions between Hyperdrives and the local filesystem. * https://docs.holepunch.to/building-blocks/hyperdrive * https://docs.holepunch.to/helpers/mirrordrive * https://docs.holepunch.to/helpers/localdrive ## Tutorial Start by creating the drive-writer-app project with these commands: ```bash mkdir drive-writer-app cd drive-writer-app pear init -y -t terminal npm install corestore localdrive hyperswarm hyperdrive debounceify b4a bare-process ``` Alter driver-writer-app/index.js to the following: ```js import Hyperswarm from 'hyperswarm' import Hyperdrive from 'hyperdrive' import Localdrive from 'localdrive' import Corestore from 'corestore' import debounce from 'debounceify' import b4a from 'b4a' import process from 'bare-process' // create a Corestore instance const store = new Corestore(Pear.config.storage) const swarm = new Hyperswarm() Pear.teardown(() => swarm.destroy()) // replication of the corestore instance on connection with other peers swarm.on('connection', conn => store.replicate(conn)) // A local drive provides a Hyperdrive interface to a local directory const local = new Localdrive('./writer-dir') // A Hyperdrive takes a Corestore because it needs to create many cores // One for a file metadata Hyperbee, and one for a content Hypercore const drive = new Hyperdrive(store) // wait till the properties of the hyperdrive instance are initialized await drive.ready() // Import changes from the local drive into the Hyperdrive const mirror = debounce(mirrorDrive) const discovery = swarm.join(drive.discoveryKey) await discovery.flushed() console.log('drive key:', b4a.toString(drive.key, 'hex')) // start the mirroring process (i.e copying) of content from writer-dir to the drive // whenever something is entered (other than '/n' or Enter )in the command-line process.stdin.on('data', (data) => { data = data.toString() if (!data.match('\n')) return mirror() }) // this function copies the contents from writer-dir directory to the drive async function mirrorDrive () { console.log('started mirroring changes from \'./writer-dir\' into the drive...') const mirror = local.mirror(drive) await mirror.done() console.log('finished mirroring:', mirror.count) } ``` Open the drive-writer-app with pear dev: ```bash cd drive-writer-app pear dev ``` The drive-writer-app creates a LocalDrive instance for a local directory and then mirrors the LocalDrive into the Hyperdrive instance. The store used to create the Hyperdrive instance is replicated using Hyperswarm to make the data of Hyperdrive accessible to other peers. It outputs a key which will be passed to drive-reader-app upon execution. Leave the driver-writer-app running and in a new terminal create the drive-reader-app project with these commands: ```bash mkdir drive-reader-app cd drive-reader-app pear init -y -t terminal npm install corestore localdrive hyperswarm hyperdrive debounceify b4a ``` Adjust the drive-reader-app/index.js file to: ```js import Hyperswarm from 'hyperswarm' import Hyperdrive from 'hyperdrive' import Localdrive from 'localdrive' import Corestore from 'corestore' import debounce from 'debounceify' import b4a from 'b4a' const key = Pear.config.args[0] if (!key) throw new Error('provide a key') console.log('provided key:', key.toString('hex')) // create a Corestore instance const store = new Corestore(Pear.config.storage) const swarm = new Hyperswarm() Pear.teardown(() => swarm.destroy()) // replication of store on connection with other peers swarm.on('connection', conn => store.replicate(conn)) // create a local copy of the remote drive const local = new Localdrive('./reader-dir') // create a hyperdrive using the public key passed as a command-line argument const drive = new Hyperdrive(store, b4a.from(key, 'hex')) // wait till all the properties of the drive are initialized await drive.ready() const mirror = debounce(mirrorDrive) // call the mirror function whenever content gets appended // to the Hypercore instance of the hyperdrive drive.core.on('append', mirror) const foundPeers = store.findingPeers() // join a topic swarm.join(drive.discoveryKey, { client: true, server: false }) swarm.flush().then(() => foundPeers()) // start the mirroring process (i.e copying the contents from remote drive to local dir) mirror() async function mirrorDrive () { console.log('started mirroring remote drive into \'./reader-dir\'...') const mirror = drive.mirror(local) await mirror.done() console.log('finished mirroring:', mirror.count) } ``` The drive-reader-app creates a LocalDrive instance for a local directory and then mirrors the contents of the local Hyperdrive instance into the LocalDrive instance (which will write the contents to the local directory). In a new terminal, execute the drive-reader-app with pear dev, passing the key that the drive-writer-app already output: ```bash cd drive-reader-app pear dev . <SUPPLY_KEY_HERE> ``` LocalDrive does not create the directory passed to it until something has been written, so create the drive-writer-app/writer-dir (mkdir writer-dir) and then add/remove/modify files inside drive-writer-app/writer-dir then press Enter in the writer's terminal (to import the local changes into the writer's drive). Observe that all new changes mirror into reader-app/reader-dir. Just as a Hyperbee is just a Hypercore, a Hyperdrive is just a Hyperbee - which is just a Hypercore. In a new terminal, create the bee-reader-app project with these commands: ```bash mkdir bee-reader-app cd bee-reader-app pear init -y -t terminal npm install corestore hyperswarm hyperdrive debounceify b4a bare-process ``` Adjust the bee-reader-app/index.js file to: ```js import Hyperswarm from 'hyperswarm' import Corestore from 'corestore' import Hyperbee from 'hyperbee' import debounce from 'debounceify' import b4a from 'b4a' import process from 'bare-process' // create a Corestore instance const store = new Corestore(Pear.config.storage) const swarm = new Hyperswarm() Pear.teardown(() => swarm.destroy()) // replicate corestore instance on connection with other peers swarm.on('connection', conn => store.replicate(conn)) // create/get the hypercore instance using the public key supplied as command-line arg const core = store.get({ key: b4a.from(process.argv[3], 'hex') }) // create a hyperbee instance using the hypercore instance const bee = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'json' }) // wait till the properties of the hypercore instance are initialized await core.ready() const foundPeers = store.findingPeers() swarm.join(core.discoveryKey) swarm.flush().then(() => foundPeers()) // execute the listBee function whenever the data is appended to the underlying hypercore core.on('append', listBee) listBee() // listBee function will list the key-value pairs present in the hyperbee instance async function listBee () { console.log('\n***************') console.log('hyperbee contents are now:') for await (const node of bee.createReadStream()) { console.log(' ', node.key, '->', node.value) } } ``` Now the Hyperdrive can be inspected as though it were a Hyperbee, and log out some file metadata. Execute the bee-reader-app with pear dev, passing it the key output by the driver-writer-app: ```bash cd bee-reader-app pear dev . <SUPPLY_KEY_HERE> ``` The bee-reader-app creates a Hyperbee instance using the Hypercore instance created with the copied public key. Every time the Hyperbee is updated (an append event is emitted on the underlying Hypercore), all file metadata nodes will be logged out. Try adding or removing a few files from the writer's data directory, then pressing Enter in the writer's terminal to mirror the changes.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully