browserifyp2phypercore-protocol

Trying to Browserify the hyperswarm library to make a connection to a topic from a browser


I am trying to create a hyperswarm network between multiple node servers (which works fine) and also a browser instance (which doesn't).

I thought that I could browserify the server.js code like I would do if I wanted to run express.js in the browser, but I'm getting a weird error: bundle.js:12852 Uncaught SyntaxError: Unexpected token '{'

Here is the server.js code I browserified:

var Datastore = require('nedb')
  , db = new Datastore({ filename: 'spsn_db/usersdb.json', autoload: true });

const hyperswarm = require('hyperswarm')
const crypto = require('crypto')

const swarm = hyperswarm()

// look for peers listed under this topic
const topic = crypto.createHash('sha256')
  .update('mycoolstuff') // some topic to connect
  .digest()

swarm.join(topic, {
  lookup: true, // find & connect to peers
  announce: true // optional- announce self as a connection target
})

swarm.on('connection', (socket, info) => {
    const {
        priority,
        status,
        retries,
        peer,
        client
    } = info

    if (client) {
        let doc
        socket.on("data", data => {
            doc = {
                "name":data.toString()
            }
            db.insert(doc, function (err, newDoc) { 
                //writes the received data
            });
        })

    }
    else {
        socket.write(Buffer.from("send some data to write", 'utf8'))
    }
})

Here is index.html:

<script src="bundle.js"></script>

I figured it would work the same way between the node server and the html instance since server.js was browserified. What am I missing?


Solution

  • Unfortunately, the swarm elements of the hypercore protocol do not work in mainstream browsers, due to API limitations (of the browsers). You'd need to rely on webRTC to do peer to peer browser things. This comes with its own setup requirements.

    A way of doing it would be to do a websocket connection to a remote node hyperswarm.

    You might want to look at hyper-sdk. This is a version of the hypercore stack setup to be browserify-able.

    Update: there is also now dht-relay which could allow one to remotely connect into the hyperswarm dht.

    Also the beaker, gateway and agregore browsers which are set up for peer-to-peer operation.