Currently I dont use connection pooling on my settings since i only have 1-4 users in the application.
According to the doc this is the recommended way.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Now, what i did was export the connection object and shared it to other api resources.
On db.js file
var mysql = require('mysql');
var connection = mysql.createConnection({ ... });
module.exports = connection;
On api.js file
const express = require('express');
const router = express.Router();
const conn = require('./db');
router.post('/create', function (req, res) {
connection.query('INSERT ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
router.post('/update', function (req, res) {
connection.query('UPDATE SET ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
AND SO ON the same goes to the other api resources that was omitted in these examples..
What is the drawback in this connection design?
Please correct me if I'm wrong. I think, even though you export the connection object, you're still managing the connection one by one.
Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources
Wikipedia
And from the same doc,
This is because two calls to pool.query() may use two different connections and run in parallel
So the best way is to use pool for managing the connections
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
Hope that helps.
Related
I tried to close the connection for the below query by using connection.close(). but it is not working, so how to close connection inside route file
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
var db = require('../database.js');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query("Select users..... ",function(err,supervisorrows) {
if(err){
req.flash('error', err);
res.render('View',{page_title:"Users - Node.js",supervisor:''});
}else{
res.render('View',{page_title:"Users - Node.js",supervisor:supervisorrows.recordset});
}
});
module.exports = router;
According to mysql npm docs There are two ways to end a connection :
connection.end() method
connection.destroy() method
The first one will make sure all previously enqueued queries are still before sending a COM_QUIT packet to the MySQL server.
The second one terminates a connection immediately and guarantees that no more events or callbacks will be triggered for the connection.
I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.
An example of connection file: db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
and one of the various files to manage the routes:
const app = express();
const router = express.Router();
const db = require('./db');
router.get('/save',function(req,res){
// some code for db
});
module.exports = router;
Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?
How many times will my connection be created?
There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:
require("./db") === require("./db") // true
Im using node js and I cant figure out how to check if my WebSocket.Server connection is Open or Closed, is there any function like socket.readyState?
Im asking because I have a problem, when me + someone else reloads the 192....../xxx in the same moment I get an error Error: listen EADDRINUSE :::3001 and I cant figure out where it blows up..
Also Id like to mention that I DO close the connection but only in one spot, here is my code example;
router.get('/', function(req, res, next) {
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('Client: Im on... /zzz');
})
});
wss.on('error', function error(err) {
console.log(wss.clients);
next(err);
});
//??
//wss.clients.clear();
db.all('SELECT rowid, * FROM ZZZZZZZZ', (err, rows) => {
//idk if its ok
if (err) next(err);
if (rows.length == 0) {
res.render('xxxxx/index', {
AAA: 'empty'
});
} else {
wss.close(function(err) {
if (err) next(err);
console.log('closing websocket at /zzz');
server.close();
setTimeout(function() {
wss = new WebSocket.Server({
port: 3001
});
}, 100);
});
res.render('xxx/index', {
AAA: rows
});
}
});
});
And heres what I have above my router.get
let express = require('express');
let router = express.Router();
let sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./xx/xx/xx/xxx/xx/xxx.db');
let WebSocket = require('ws');
let wss = new WebSocket.Server({ port: 3001 });
let server = wss._server;
Looks to me like you have the websocket server depend on a specific endpoint. The error you're getting is trying to tie multiple websocket servers to the same port. You only really need one websocket server to handle multiple client connections. I suggest that you would make them separate and have the websocket server run alongside of the express app.
Having endpoints to perform certain actions like closing the websocket is cool, but I would suggest authenticating them if you're doing something like that.
The error you are having is 100% server side, port 3001 is in use. It's trying to start up a websocket server on port 3001 and there is already one running. You can either use different ports, or just use the original websocket server to serve multiple clients.
To actually answer the question you asked, I believe the proper way for doing so would be to implement a heartbeat for your websocket server. That should send after n amount of minutes/seconds/milliseconds (I'd probably go with minutes). It's a good idea to have it bidirectional so your server and clients know when a connection has been dropped.
const mysql = require('mysql');
let connection = mysql.createConnection(...);
connection.connect((err)=>{
...
connection.query((err)=>{
...
connection.end();});
});
After I close the connection by using
connection.end()
, if I want to query the database again using the same credentials, do I need to make a new connection by calling
mysql.createConnection(...)
Or can I reuse the same connection by simply calling
connection.connect(...)
A little background: I'm deploying an angular/node.js app to a shared hosting website, and the web host has a maximum limit of 25 concurrent connections to mySQL database, therefore I need to make sure I close a connection properly after a user does his query. I am not sure if I could reuse the connection created by mysql.createConnection(...) after I close that connection, or do I need to create a brand new connection.
You can use one global connection for getting data from db .
If You working on single file than you can write as
app.js one file only
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
if you want to use same connection in multiple file than you can write as
app.js
app.use(
connection(mysql, {
host: xxxxx,
user: 'root',
password : xxxx,
port : 3306,
database:dbname
},'pool'),
);
var oem = require('./routes/type');
app.get('/api/oemtype',oem.type);
For the second file
type.js
exports.type = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM type',function(err,rows)
{
if(err)
res.json({
status:0
});
res.send(rows);
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
No need to use of connection.end().
I am using NodeJs along with MySQL. I am using node-mysql after looking at MySQL with Node.js. Now the problem is I am trying to make db connection only once and using GETs inside it but it's not working.
Code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
app.get('/hello',function(req,res){
console.log('Hello');
res.send('Hi');
});
});
But the above code is not working. It is not recognizing the route. But making a connection inside every get function works.
I should be doing something wrong. Is there any way such that I can connect to the Db only once ?
You should move your call to app.get to the top level scope of the file. These calls are declarative and should be thought of more like configuring your application than the application's business logic. From the mysql docs, the connection object will automatically implicitly open a connection to the database if connection.query is called and a connection is not yet established. That sounds like the mechanism you should take advantage of.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
app.get('/hello',function(req,res){
console.log('Hello');
connection.query('select * from users', function (error, result) {
res.send('Hi');
});
});