Doubt with syntax

3

Simple doubts. Usually I see this syntax:

require('../lib/dbconnect')(config);

But I do not understand why I use these parentheses in this way.

(....)(....);

Can anyone explain what it's all about?

    
asked by anonymous 15.10.2015 / 15:06

2 answers

4

This require('../lib/dbconnect')(config); syntax is used when the module needs to be configured.

That is, in the module code there is something like:

var mysql = require('mysql');

module.exports = function (options) {

    var connection = mysql.createConnection({
        host: options.url,
        user: options.user,
        password: options.pass,
        database: options.database
    });
    connection.connect();

    return connection.query; // que é uma função
}

This is very common when you want to pass url , secret key, database ip, translation or other to a module.

Once configured it is used as usual:

var db = require('../lib/dbconnect')(config);
db.query('SELECT * FROM tabela', function(err, dados){
    // etc
});

An example in JavaScript not necessarily in Node environment would be a speed converter, that's what occurred to me now! : P

function velocidade(conf){
    return function(KmHora){
        var velocidade = typeof KmHora == 'number' ? KmHora : parseInt(KmHora, 10);
        var ms = velocidade * conf.fator;
        return [ms, conf.unidade].join(' ');
    }
}

So we can set the unit, and the multiplication factor.

var converter = velocidade({unidade:'m/s', fator: 1/3.6});

And then use the function in n different values:

console.log(converter('300 km/h')); // 83.33333333333334 m/s
console.log(converter(116)); // 32.(2) m/s
console.log(converter(36)); // 10 m/s

jsFiddle: link

    
15.10.2015 / 15:12
6

It's equivalent to doing it here:

var db = require('../lib/dbconnect');
db(config);

The require function returns the exported value in the dbconnect.js file. This module exported a single function, which you are calling by passing config as a parameter.

    
15.10.2015 / 15:13