At first, import the ‘data_base’ using the following statement:
let data_base = require('database');
Secondly, establish a connection to the database by calling the createConnection() method and provide information on data_base server such as host, user, password and database as follows:
let connection = data_base.createConnection({host: 'localhost' ,user: 'root' ,password: ' ', database: 'todoapp'});
Here, we created a connection to todoapp database in the local database server.
Now, call the connect() method on the connection object to connect to the data_base database server:
connection.connect(function(err) {
if (err) { return console.error('error: ' + err.message); }
console.log('Connected to the data_base server.');
});
The connect() method accepts a callback function that has the err argument which provides the detailed error if any error occurred.
If the program shows the following result, the program is successful:
> node connect.js
Connected to the data_base server