To get started, inside the Terminal, let's go ahead and install the most recent version of Socket.io using npm i. The module name is socket.io, and the most recent version at time of writing is @2.0.4. We'll use the --save dev flag to update the package.json file:
npm i socket.io@2.0.4 --save
Once this is in place, we can go ahead and make a few changes to our server file. First up, we'll load in the library. I'll make a constant called socketIO and set it equal to the require statement for the socket.io library:
const path = require('path');
const express = require('express');
const socketIO = require('socket.io');
With this in place, we now need to integrate Socket.io into our existing web server. Currently, we use Express to make our web server. We create a new Express app, we configure our middleware, and we call app.listen:
var app = express();
app.use(express.static(publicPath));
app.listen(port, () => {
console.log(`Server is up on ${port}`);
});
Now, behind the scenes, Express is actually using a built-in Node module called http to create this server. We'll need to use http ourselves. We need to configure Express to work with http. Then, and only then, will we also be able to add Socket.io support.