I'm a beginner with Node.js, is it ever ok to use MySQL as a global var?
I have a db_helper.js with this code inside:
global.client = require('mysql').createConnection({
user: '__mysqluser__',
password: '__mysqlpass__',
database: '__mysqldb__',
timezone: '-03:00'
});
global.client.connect();
On my main.js I just do a:
require('db_helper');
Then on other js files, whenever I need to UPDATE or SELECT I just call:
global.client(query, data);
I haven't seen any code like this yet, but it works as expected, but I'm experiencing random crashes from time to time, when reloading pages.
Is it OK to use it like this? Are my crashes related to the way I connect to the DB?
I think it's related because when the crash happens, is because MySQL fails to return data, but the crash happens when parsing the result, like:
global.client.query(query, function(err, results, fields) {
if (err) throw err;
if (results && Object.prototype.toString.call(results) === '[object Array]') {
var j = result[0].data;
}
}
Most of the time, var j has the value I expect it to have, but when node crashes, this var returns empty, despite the fact that it checks for (results) consistency before. Node crashes saying:
result[0].data is undefined
Thanks.
EDIT: The crash happens whenever the client js file gets updated on server. (after a local edit of the .js file & server upload via FTP), Why?