E
E
Egor Mikheev2016-11-04 10:07:37
Node.js
Egor Mikheev, 2016-11-04 10:07:37

What is the danger of using global variables in node.js?

I decided to move the implementation of DB models and methods to a separate file, using global variables. Is it allowed to do so? And what problems might arise?
index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

require('./js/dbmodels.js');

io.on('connection', function(socket){
  socket.on('get-struct message', function(data){
 
      global.Decode('sZ5gz9EBe959XKgnsdEwNN7QLAKK6vnxQMnhEuKDT0g').then(function(result){
        console.log(result);
      });
    socket.emit('get-struct message', data);
  });
});
 
});

dbmodels.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('mysql://datas:[email protected]:5543/datas');
var MCrypt = require('mcrypt').MCrypt;

global.Registry = sequelize.define('registry', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    sub_id: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    item: {
        type: Sequelize.CHAR()
    },
    value: {
        type: Sequelize.TEXT
    },
    up_date: {
        type: Sequelize.DATE,
        defaultValue: Sequelize.NOW
    }
},{
    timestamps: false,
    freezeTableName: true
});

global.getRegistry = function (value) {
    return global.Registry.findOne({
        where: {item: value},
        attributes: ['value']}).then(function (result) {
        return result.value;
    });
};

global.Decode = function (value) {
    return global.getRegistry('module_crypt_key').then(function (secret) {
        var desEcb = new MCrypt('rijndael-256', 'ecb');     
        desEcb.open(secret);
        return desEcb.decrypt(new Buffer(value, 'base64')).toString();
        
    });
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OnYourLips, 2016-11-04
@OnYourLips

You are masking dependencies, it will be difficult to maintain such code.
Try to accept all dependencies for each "class" explicitly, through one method. I repeat: do not ask, but accept.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question