nodejs socket es6

NodeJS Socket ES6

NodeJS is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Socket is a communication protocol used to establish a connection between a client and a server. ES6 is the sixth version of the ECMAScript language standard for JavaScript.

Using NodeJS Socket with ES6

To use NodeJS socket with ES6, we need to import the socket module using the import statement:


import socket from 'socket.io';

After importing the socket module, we can create a socket instance by passing the server object as a parameter:


const io = socket(server);

Now, we can listen to various socket events by using the on method:


io.on('connection', (socket) => {
  console.log('a user connected');
});

In the above code, we listen to the 'connection' event and print a message when a user connects to the server.

Alternative Way to Use NodeJS Socket with ES6

Another way to use NodeJS socket with ES6 is by using the require statement:


const socket = require('socket.io')(server);

In this method, we pass the server object as a parameter to the require statement and create a socket instance.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe