Getting started

  1. Installation
  2. Examples
  3. Usage
    1. Server
    2. Client

Installation

ShareDB is distributed through npm:

npm install --save sharedb

If your server and client have separate dependencies, ShareDB should be added as a dependency to both packages.

You may also wish to install other OT types.

Examples

There are working examples in the git repository.

Usage

Server

The following is an example using Express and ws.

The ShareDB backend expects an instance of a Stream, so this example also uses @teamwork/websocket-json-stream to turn a WebSocket into a Stream.

var express = require('express')
var WebSocket = require('ws')
var http = require('http')
var ShareDB = require('sharedb')
var WebSocketJSONStream = require('@teamwork/websocket-json-stream')

var app = express()
var server = http.createServer(app)
var webSocketServer = WebSocket.Server({server: server})

var backend = new ShareDB()
webSocketServer.on('connection', (webSocket) => {
  var stream = new WebSocketJSONStream(webSocket)
  backend.listen(stream)
})

server.listen(8080)

This server will accept any WebSocket connection on port 8080, and bind it to ShareDB.

Client

This client example uses reconnecting-websocket to reconnect clients after a socket is closed.

Try running the working example to see this in action.

var ReconnectingWebSocket = require('reconnecting-websocket')
var Connection = require('sharedb/lib/client').Connection

var socket = new ReconnectingWebSocket('ws://localhost:8080', [], {
  // ShareDB handles dropped messages, and buffering them while the socket
  // is closed has undefined behavior
  maxEnqueuedMessages: 0
})
var connection = new Connection(socket)

var doc = connection.get('doc-collection', 'doc-id')

doc.subscribe((error) => {
  if (error) return console.error(error)

  // If doc.type is undefined, the document has not been created, so let's create it
  if (!doc.type) {
    doc.create({counter: 0}, (error) => {
      if (error) console.error(error)
    })
  }
});

doc.on('op', (op) => {
  console.log('count', doc.data.counter)
})

window.increment = () => {
  // Increment the counter by 1
  doc.submitOp([{p: ['counter'], na: 1}])
}

This example uses the json0 type (ShareDB’s default type).