Node js MySQL connection:
This is the post for MySQL and Node JS connectivity. We can connect MongoDB and MySQL to Node JS.
It is an open-source, cross-platform JavaScript run-time environment. This executes JavaScript code outside of a browser. It’s work as a server-side script. For node.js we need to install the node.js in our machine. You can download the latest version of node js from here.
Download node.js
To make a connection with MySQL in node js, we have to install MySQL module first. it is very easy to do that. Please follow the following steps –
Step 1 : Open the “node_modules” directory under the project directory, then change this directory in command prompt and use the command “npm install mysql”
Step 2 : Make a js file named “databaseConnection.js” in routes folder in the project directory. Paste the following code there.
var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var conn = mysql.createConnection({ host:'localhost', user: 'root', password: '****', database: 'databaseName' }); conn.connect(function(err){ if(err) throw err; console.log('database Connected'); }); module.exports = conn;
Step 4 : Make a new database and run the program.