Under the Windows platform, test the Nodejs connection to the MySQL database.
First install MySQL dependency package in the console npm install MySQL
After the installation is successful, the MySQL dependency package can be found in the Node_modules folder in the user directory
Then create a new JS file to test the MySQL connection mysqltest.js
var mysql = require (' mysql '); var connect = mysql.createconnection ({ host:' localhost ', User:' root ', Password:", Database:' Test ', port:3306}); Connect.connect (); Console.log ("MySQL has connnected"), Connect.end (); Console.log ("MySQL has colsed");
If the Mysqltest.js file is not in the user directory, the mysqltest.js is placed in the Nodejs folder on the E drive, and node mysqltest.js will be reported cannot find module ' mysql ' Error
This is because node is executing mysql.js in the E:\NodeJS directory, and node cannot find the MySQL module in the Nodejs directory, so this error is reported.
Workaround:
You can put the Mysqltest.js file in the user directory, and then node mysqltest.js;
You can also install the MySQL dependency package in the Nodejs directory, and then node mysqltest.js;
There are two ways to install a dependency package in the Nodejs directory:
1. Direct console into the Nodejs directory, then npm install MySQL
2. Create a Package.json file in the Nodejs directory, add MySQL dependencies, and then perform NPM install in the Nodejs directory
{ "name": "Mysqltest", "description": "Test Project", "version": " 0.0.1 ", true, " Devdependencies ": { " mysql ":" 2.6.2 " }}
If you need to add multiple dependent packages, the second way is more convenient
Nodejs cannot find module ' mysql ' Problem analysis