NPM MySQL package installation fails in Node.js project

I’m having trouble getting the MySQL package to work properly in my Node.js application. Even though the npm install command seems to run without errors, my Node.js script can’t find the mysql module when I try to run it.

I’ve tried installing different versions of the mysql package but keep getting the same “Cannot find module ‘mysql’” error. The installation appears successful in the terminal, showing that dependencies are being downloaded and installed. However, when I check my project directory, the mysql package doesn’t seem to be properly added to the node_modules folder.

Here’s what happens when I try to run my database connection script:

const database = require('mysql');

const connection = database.createConnection({
  host: 'localhost',
  user: 'admin',
  password: 'secret123',
  database: 'my_app_db'
});

connection.connect(function(error) {
  if (error) {
    console.error('Database connection failed: ' + error.stack);
    return;
  }
  console.log('Connected to database with ID ' + connection.threadId);
});

The error shows that Node.js can’t locate the mysql module even though npm says it installed successfully. Has anyone encountered this issue before? What could be causing this problem?

Check your require path first - I always mix up ‘mysql2’ vs regular ‘mysql’ depending on what I actually installed. If that’s not it, try ‘npm cache clean --force’ to clear the cache. Fixed similar weird module issues for me before. Sometimes node_modules gets corrupted even when the install looks fine.

Classic npm workspace issue. You probably installed globally with -g or your package.json got corrupted. Delete node_modules and package-lock.json, then run npm install mysql again. Don’t use sudo on Linux/Mac - it screws up permissions. Also check your Node version since older ones have module resolution bugs. Run “node -e “console.log(require.resolve(‘mysql’))”” to see where Node’s actually looking for the module. If that fails, your install didn’t work despite what the terminal said.

Had this exact problem six months ago - drove me nuts for hours. You’re probably running your node script from a different directory than where you installed mysql. Node looks for modules relative to your script’s location, not where you ran npm install. Run both npm install and your script from the same project root. Also check for multiple package.json files in different folders - I had nested projects that broke module resolution. Run “npm list mysql” from your script’s directory to verify it’s actually installed there. If it’s empty or errors out, you’re in the wrong spot or the install failed.