Error: Cannot find module 'socket.io' when trying to run a simple server js file

Issue

Here is my server.js file I am trying to run using node server.js:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket-io')(http); //also tried socket.io instead of socket-io

io.on('connection', (socket) => {
console.log('User Online');

    socket.on('canvas-data', (data) => {
        socket.broadcast.emit('canvas-data', data);

    })
})

    var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
    http.listen(server_port, () => {
        console.log("Started on : " + server_port);
})

And here is the full error:

internal/modules/cjs/loader.js:311
  throw err;
  ^

Error: Cannot find module 'C:\Users\rami_\OneDrive\Skola\Utbildning\White board\server\node_modules\socket-io\index.js'. Please verify that the package.json has a valid "main" 
entry
at tryPackage (internal/modules/cjs/loader.js:303:19)
at Function.Module._findPath (internal/modules/cjs/loader.js:516:18)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:867:27)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\rami_\OneDrive\Skola\Utbildning\White board\server\server.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32) {
  code: 'MODULE_NOT_FOUND',
  path: 'C:\\Users\\rami_\\OneDrive\\Skola\\Utbildning\\White board\\server\\node_modules\\socket-io\\package.json',
  requestPath: 'socket-io'
}

I have run npm install socket-io and inside the node_modules folder I can see a folder named socket-io.

Solution

You have the wrong package name, it is socket.io, change the require to require('socket.io') and re-install it with npm, you’re trying to use a deprecated package.

Answered By – Liam

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.