How to provide a mysql database connection in single file in nodejs

0 votes

I need to provide the mysql connection for modules. I have a code like this.

var express = require('express'),
app = express(),
server = require('http').createServer(app);

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database    : 'chat'
});

connection.connect(function(err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
});

app.get('/save', function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    var query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
        if (err) throw err;
    });
});

server.listen(3000);

But how we provide one time mysql connection for all the modules?

Oct 15, 2020 in Node-js by kartik
• 37,510 points
8,482 views

1 answer to this question.

0 votes

Hello @kartik,

You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler.

You could create db.js:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database : 'chat'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

Then in your app.js, you would simply require it.

var express = require('express');
var app = express();
var db = require('./db');

app.get('/save',function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    db.query('INSERT INTO messages SET ?', post, function(err, result) {
      if (err) throw err;
    });
});

server.listen(3000);

This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db.

Hope it helps!!

Get your Node.js Certification today to become a certified expert.

Thank you!!

answered Oct 15, 2020 by Niroj
• 82,880 points

Related Questions In Node-js

0 votes
0 answers

How to append to a file in Node?

I am trying to append a string to a ...READ MORE

Jul 9, 2020 in Node-js by kartik
• 37,510 points
769 views
0 votes
1 answer

How to update a value in a json file and save it through node.js?

Hello @kartik, It's particularly useful if you're concerned ...READ MORE

answered Oct 12, 2020 in Node-js by Niroj
• 82,880 points
25,370 views
0 votes
1 answer

How to split and modify a string in NodeJS?

Hello @kartik, Use split and map function: var str = "123, 124, 234,252"; var ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,880 points
877 views
0 votes
1 answer

How to check if a collection exists in Mongodb native nodejs driver?

Hello @kartik, The collectionNames method of the native driver's Db object accepts ...READ MORE

answered Nov 27, 2020 in Node-js by Niroj
• 82,880 points
13,732 views
0 votes
1 answer

How to write files in Node.js?

Hello @kartik, Currently there are three ways to ...READ MORE

answered Jul 8, 2020 in Node-js by Niroj
• 82,880 points
705 views
0 votes
1 answer

How to Install a local module using npm?

Hello @kartik, This is what worked for me: npm ...READ MORE

answered Jul 9, 2020 in Node-js by Niroj
• 82,880 points
8,834 views
0 votes
1 answer

How to run Gulp tasks sequentially one after the other?

Hello @kartik, By default, gulp runs tasks simultaneously, ...READ MORE

answered Jul 12, 2020 in Node-js by Niroj
• 82,880 points
1,235 views
0 votes
1 answer

How to set environment variables from within package.json?

Hello @kartik, Set the environment variable in the ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,880 points
23,160 views
0 votes
1 answer

How to append to a file in Node?

Hello @kartik, you can use appendFile, which creates a ...READ MORE

answered Jul 20, 2020 in Node-js by Niroj
• 82,880 points
504 views
0 votes
1 answer

How to get the _id of inserted document in Mongo database in NodeJS?

Hello @kartik, A shorter way than using second ...READ MORE

answered Sep 7, 2020 in Node-js by Niroj
• 82,880 points
13,176 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP