Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js node-mysql Error: EMFILE, Too many open files

The ulimit on my system is 1024. I have come across many posts regarding the same error but no concrete answer. I also want to know if this is a node/node-mysql issue and not to do with my code. I will post a snippet of my code here:

exports.fn1  = function(req,res,host,user,password,database){
        var client = connectDB.connectDatabase(host,user,password,database);
                fn2();

    function fn2() {
        client.query(
            'select statement', args,
            function selectCb(error, result, fields) {
                if (error) {
                    console.log('ERROR');
                    client.end();
                    return;
                }
              
                if(not timeout) {
                    setTimeout(function(){
                                    
                                    fn2();
                               },5000);
                }
                
                else {
                    res.writeHead(200, {'Content-Type': 'text/plain'});
                    res.write(somedata);
                    res.end(); 
                    client.end();   
                }


        });
        }
    }
};

connectDB is a module I wrote which does the db connections

var Client = require('mysql').Client; 

exports.connectDatabase = function(host,user,password,database) {
    var client = new Client(); //Database connection object
    //Credentials for DB connection
    client.host = host; 
    client.user = user;
    client.password = password;
    client.database = database;

    client.connect(function(error, results) {
        if(error) {
          console.log('Connection Error:');
          return;
        }
    });
    return client;
}

Am I doing something wrong with node.js here or is it a driver/node.js problem? Thanks for the help!

like image 322
cowboybebop Avatar asked Feb 28 '26 04:02

cowboybebop


1 Answers

I think you should be using closures more. References directly to fn2 are going to be using the named object, which will keep it from going out of scope. References to the same code through a closure will cause a layer of anonymity, which will allow the references to exit scope gracefully and get garbage collected.

like image 60
Paul Sonier Avatar answered Mar 02 '26 17:03

Paul Sonier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!