javascriptnode.jssocket.io

Why do I keep getting "Cannot find module 'socket.io'"?


I have been trying to use socket.io in my NodeJS script, but I'm constantly getting the error "Cannot find module 'socket.io'".

Full error:

$ sudo node /var/www/apache/server/serverScript.js
module.js:549
    throw err;
    ^

Error: Cannot find module 'socket.io'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/www/apache/server/serverScript.js:59:12)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

I've tried installing socket.io globally, I've updated everything npm related, and tried all other common suggestions I found online, but the error hasn't changed.

If I had to guess, I think it's related to the package.json file. I started off with NodeJS just recently, and never used a package.json file. I saw somebody mention it as a fix, so I added one through npm init. This placed it in /home/pi. Since this didn't help, I moved the file to the js file location: /var/www/apache/server. Unfortunately, no luck.

Can anyone tell me what's causing this issue?


Solution

  • It's hard to give a good answer without any of your source code. However, you can try do to this.

    1. Open your cmd or terminal.
    2. cd into your project folder.
    3. Run the command: npm i --save socket.io
    4. Within your source code, type const io = require('socket.io'); to import socket.io.