Home Guides Protocol Install Awesome Hacks
Guides Example Code

Example Code

Here are some examples to get you started with building on Hypercore Protocol.

Common Boilerplate

The examples use this common boilerplate to set up the Hyperspace Daemon connection:
import {
  Client as HyperspaceClient,
  Server as HyperspaceServer
} from 'hyperspace'

async function main () {
  // Setup the Hyperspace Daemon connection
  // =
  const {client, cleanup} = await setupHyperspace()
  console.log('Hyperspace daemon connected, status:')
  console.log(await client.status())


  await cleanup()

async function setupHyperspace () {
  let client
  let server
  try {
    client = new HyperspaceClient()
    await client.ready()
  } catch (e) {
    // no daemon, start it in-process
    server = new HyperspaceServer()
    await server.ready()
    client = new HyperspaceClient()
    await client.ready()
  return {
    async cleanup () {
      await client.close()
      if (server) {
        console.log('Shutting down Hyperspace, this may take a few seconds...')
        await server.stop()