For this you will need the following installed in your machine.
Once you have node.js installed you could use the following commands to check that node.js and npm is properly installed. As you install node.js, npm should have also been installed. npm is a package manager for node.js.
Now we will create a folder that will become our project folder. If you want to do this through command prompt you could use the “mkdir” command and “cd” into the folder.
Once you are in the right location we could now use npm to initiate the project and install the MySQL driver. To do this, you have make sure you are running the command prompt as an administrator. If were not, no problem! Before you re-start the command prompt, do a right-click and choose “Run as administrator.”
You will know if you are running it as an administrator as it will be labeled accordingly on the window.
Once you’ve confirmed that you are running the command prompt as an administrator, go to your project location (using “cd“) and initialize the project (“npm init -y“) with npm.
Now you can install the MySQL driver using npm (“npm install mysql“). You could see that in the example below, we are checking the contents of the folder after the installation. If were not running the command prompt as an administrator, your installation might stall or report errors.
Now let’s go back to MySQL Workbench and do a couple configurations to prepare. Let’s first check that you are locally connecting as ‘root’. You could do this by going to “Database” then “Manage Connections” and check that your local instance is using the Username “root.”
Once that is confirmed, run the two commands, one after the other through MySQL Workbench. Make sure to use your actual password in the first command below.
ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘[YOUR-PASSWORD]‘;
Now let’s go back to the command prompt and run Visual Studio Code in the project location. You could do this by running the command “code .” at your project location.
Once you’re in VS Code, goto “File“, then click “New File” and let’s create a js file to test our connection.
Once you’ve created the js file, try the code below. When you do, make sure you are using your own password for the password.
In the VS Code menu, find “Run” and choose “Start Debugging.”
You will then choose Node.js for the debugger.
Once you run the script and get the output below, you’ve succeeded in making the connection to your database.
As the message is saying, congratulations!!