Build a Realtime Editor Using Socket.IO

Build a Realtime Editor Using Socket.IO

In this post, we will build an online text editor that allows real-time collaboration.

We will use SocketIO to stream the changes in the text in realtime, so users can see them instantly. Read on.

Project setup

We need to have Nodejs installed in our machine if you don’t have it in your machine go to Nodejs download pageand download the binary for your machine.

Now, we have the Nodejs installed, we will scaffold a new project:

mkdir realtime-editor
cd realtime-editor
npm init --y

The last command creates a package.json file in the realtime-editor project folder.

Installing SocketIO

Now, we will install SocketIO:

npm i socket.io

Socket.IO enables real-time bidirectional event-based communication. It consists of:

Next, we install the client library for SocketIO.

npm i socket.io-client

Building the server

The server will be responsible for routing our socket streams to all other sockets connected to the server socket. The server will listen to the connection on a port, and establish io connections:

const log = console.log

// initialize http server, socket.io and port number
const http = require('http').createServer()
const io = require('socket.io')(http)
const port = 3000
http.listen(port, () => log(`server listening on port: ${port}`))
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
io.on('disconnect', (evt) => {
    log('some people left')
})

We set up a connection event, the function callback has a socket argument. The socket registers a message event, it has a handler function that broadcast the data evt passed to it to all other sockets connected to the server when the message event is fired.

Building the client

We have index.html:

<html>
<title>Realtime Editor/Collaboration</title>

<body>
    <h3>Realtime Editor/Collaboration</h3>
    <div>
        <textarea rows="30" cols="50" id="editor" style="background-color:dimgrey;color:white" placeholder="Type Your Text..."></textarea>
    </div>
</body>
<script src="../node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="./client.js"></script>
</html>

See the textarea, that’s where we will type in our text. It has id editor. We make textarea have the background color dimgrey, and the text color is white.

Next, we import the socket.io-client via the script tag. Lastly, we import the client.js.

Let’s create client.js and add some code:

// client.js

var socket = io('http://localhost:3000');
const l = console.log
function getEl(id) {
    return document.getElementById(id)
}
const editor = getEl("editor")
editor.addEventListener("keyup", (evt) => {
    const text = editor.value
    socket.send(text)
})
socket.on('message', (data) => {
    editor.value = data
})

We initialized a connection to our server, then we got hold of the textarea in the DOM via its id editor. We added an event listener keyup with a callback function, this function will be executed when we type in the textarea. This callback retrieves the text const text = editor.value in the textarea via it's HTMLTextareaElement, then the text is sent over the socket stream socket.send(text).

We registered a message event with a handler that sets the text in the textarea with the data it receives.

Now, all sockets register the message event so when a user in the site types a character in the textarea, the text in the user’s textarea is sent over the socket to the server. The server then broadcasts the text to all connected users via the code:

...
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
...

As all users have a message event they are listening to, the message handler will be executed because the server emitted a message event, so all user’s textarea will be set with the text passed over the socket connection.

With these now, all users will see changes and edits by other users realtime. People can work on a document realtime. Writes can work on a blog post, article, news or novel realtime.

Running the app

Type the below command to run the server.js file:

node server

Now, open your browser and load index.htmlon it. Open another browser and load the index.html

Stack the browser windows side by side, then type a text in one browser, you will see it appear in the other browser. Anything you do in one browser will reflect realtime in the other browser, whether it is writing, deleting, etc

Conclusion

That is it with our real-time collaboration platform. You see how easy it is to implement most of the sophisticated platform in simple terms.

The main code here, was just to detect when a character is typed in, then send the text over the socket stream. The server socket having a message event registered sends the text stream over to all connected sockets. Then, all users registered the message event, will get the text stream from the server and set the textarea with the text stream.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Recommended Reading

Build a Real-time Voting App with Pusher, Node and Bootstrap

Build a Slack Polling App with Airtable, Standard Library, and Node.js

Node 12 - What Are The New Improvements And Features?

Learn full about Crash course on REST, GraphQL and Graphback

React + Node.js - Drag and Drop Multiple Files Upload

We will use SocketIO to stream the changes in the text in realtime, so users can see them instantly. Read on.

Project setup

We need to have Nodejs installed in our machine if you don’t have it in your machine go to Nodejs download pageand download the binary for your machine.

Now, we have the Nodejs installed, we will scaffold a new project:

mkdir realtime-editor
cd realtime-editor
npm init --y

The last command creates a package.json file in the realtime-editor project folder.

Installing SocketIO

Now, we will install SocketIO:

npm i socket.io

Socket.IO enables real-time bidirectional event-based communication. It consists of:

Next, we install the client library for SocketIO.

npm i socket.io-client

Building the server

The server will be responsible for routing our socket streams to all other sockets connected to the server socket. The server will listen to the connection on a port, and establish io connections:

const log = console.log

// initialize http server, socket.io and port number
const http = require('http').createServer()
const io = require('socket.io')(http)
const port = 3000
http.listen(port, () => log(`server listening on port: ${port}`))
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
io.on('disconnect', (evt) => {
    log('some people left')
})

We set up a connection event, the function callback has a socket argument. The socket registers a message event, it has a handler function that broadcast the data evt passed to it to all other sockets connected to the server when the message event is fired.

Building the client

We have index.html:

<html>
<title>Realtime Editor/Collaboration</title>

<body>
    <h3>Realtime Editor/Collaboration</h3>
    <div>
        <textarea rows="30" cols="50" id="editor" style="background-color:dimgrey;color:white" placeholder="Type Your Text..."></textarea>
    </div>
</body>
<script src="../node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="./client.js"></script>
</html>

See the textarea, that’s where we will type in our text. It has id editor. We make textarea have the background color dimgrey, and the text color is white.

Next, we import the socket.io-client via the script tag. Lastly, we import the client.js.

Let’s create client.js and add some code:

// client.js

var socket = io('http://localhost:3000');
const l = console.log
function getEl(id) {
    return document.getElementById(id)
}
const editor = getEl("editor")
editor.addEventListener("keyup", (evt) => {
    const text = editor.value
    socket.send(text)
})
socket.on('message', (data) => {
    editor.value = data
})

We initialized a connection to our server, then we got hold of the textarea in the DOM via its id editor. We added an event listener keyup with a callback function, this function will be executed when we type in the textarea. This callback retrieves the text const text = editor.value in the textarea via it's HTMLTextareaElement, then the text is sent over the socket stream socket.send(text).

We registered a message event with a handler that sets the text in the textarea with the data it receives.

Now, all sockets register the message event so when a user in the site types a character in the textarea, the text in the user’s textarea is sent over the socket to the server. The server then broadcasts the text to all connected users via the code:

...
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
...

As all users have a message event they are listening to, the message handler will be executed because the server emitted a message event, so all user’s textarea will be set with the text passed over the socket connection.

With these now, all users will see changes and edits by other users realtime. People can work on a document realtime. Writes can work on a blog post, article, news or novel realtime.

Running the app

Type the below command to run the server.js file:

node server

Now, open your browser and load index.htmlon it. Open another browser and load the index.html

Stack the browser windows side by side, then type a text in one browser, you will see it appear in the other browser. Anything you do in one browser will reflect realtime in the other browser, whether it is writing, deleting, etc

Conclusion

That is it with our real-time collaboration platform. You see how easy it is to implement most of the sophisticated platform in simple terms.

The main code here, was just to detect when a character is typed in, then send the text over the socket stream. The server socket having a message event registered sends the text stream over to all connected sockets. Then, all users registered the message event, will get the text stream from the server and set the textarea with the text stream.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Recommended Reading

Build a Real-time Voting App with Pusher, Node and Bootstrap

Build a Slack Polling App with Airtable, Standard Library, and Node.js

Node 12 - What Are The New Improvements And Features?

Learn full about Crash course on REST, GraphQL and Graphback

React + Node.js - Drag and Drop Multiple Files Upload

node-js javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.