node.js: importing socket.io with es6

Viewed 9535

I am writing a sample code to handle socket connections in node.js using es6 script, on importing socket.io it raises an error

import {
  PORT
} from './config';

import express from 'express';
import io from 'socket.io';

var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world')
});

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

app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`));

The error is

/index.js:17 _socket.default.on('connection', function (socket) { ^

TypeError: _socket.default.on is not a function at Object.on (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/src/index.js:15:4) at Module._compile (module.js:643:30) at Module._compile (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:83:24) at Module._extensions..js (module.js:654:10) at Object.newLoader [as .js] (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:88:7) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Function.Module.runMain (module.js:684:10) at Object. (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/@babel/node/lib/_babel-node.js:224:23) [nodemon] app crashed - waiting for file changes before starting... Successfully compiled 2 files with Babel. Successfully compiled 2 files with Babel.

1 Answers

You need to invoke function require('socket.io')() and pass there an express instance.

Please look at added code example:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
// this line \/
const io = socketIO(server);
// this line /\


io.on('connection', (socket) => {
    //...
});

server.listen(port, () => {
    //...
});
Related