0

I'm trying to install the mysql module for nodejs using npm. I'm using the windows subsystem for linux to do this. I've successfully installed using:

sudo npm install -g mysql

My console returns:

+ mysql@2.16.0
added 11 packages from 15 contributors in 5.779s

However, when importing the module using:

const mysql = require("mysql"); 

I receive the error:

module.js:550
    throw err;
    ^

Error: Cannot find module 'mysql'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/mnt/c/Users/alesi/Documents/coding/Web/Portfolio/src/servers/server.js:7:15)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)

Other modules such as querystring and nodemailer work just fine. Any ideas?

Alesi Rowland
  • 379
  • 2
  • 16
  • You're installing globally and not in the actually project node_modules. Need to `npm install --save mysql`. That should install to your project's node_modules and write to package.json as a dependency. – Isaac Vidrine Feb 27 '19 at 16:58
  • Cheers that has solved the problem. Could I ask why I can't do this globally as with other packages? Thus far I have installed other modules globally as the documentation suggests this should also work. – Alesi Rowland Feb 27 '19 at 17:08
  • Ill post an answer – Isaac Vidrine Feb 27 '19 at 17:46

1 Answers1

0

When you install a package globally, the package is usually installed in %USERPROFILE%\AppData\Roaming\npm\node_module on windows or /usr/local/lib/node_modules in unix systems. See this post.

Now in your project, when you require() something, it is looking to the current directory's node_modules folder. Because you installed the package globally, it does not exist in the project.

Running this will download the package to your project's node_modules folder, instead of global node_modules. --save will also write it as a dependency to package.json

npm install --save mysql

In my experience, global packages seem to be used for CLI's or running scripts from command prompt, and not for using in code.

Isaac Vidrine
  • 1,568
  • 1
  • 8
  • 20