Import functions from another file (node.js)

0

I have a bot.js file that would be my "main" project and inside the same folder where the bot.js is, I have Call.js and Somar.js which are just functions [call ()] and [add () ]. Is it possible to "import" these functions into bot.js and just use add () on it instead of having to write the function in the bot.js file itself?

    
asked by anonymous 05.07.2018 / 20:00

1 answer

1

You can always require of the file in question in order to use what it has, provided you have made the necessary exports in it.

No Somar.js could export whole function, using module.exports :

module.exports = (a, b) => a + b;

Then in bot.js would require to use:

const somar = require('./Somar');
console.log(somar(10, 20)); //30

Note that no require must indicate the path where the file is located. As they are in the same folder just prefix with ./ . It is also important to mention that require does not lead to file extension.

You can also export more than one function if you change the way you export. As an example, let's assume that in Call.js , you want to export two functions.

Call.js

module.exports = {
    funcao1(){
        console.log("f1");
    },
    funcao2(){
        console.log("f2");
    }
}

Now to use these functions also in bot.js would do so:

const somar = require('./Somar');
console.log(somar(10, 20)); //30

const call = require('./Call');
call.funcao1(); //f1
call.funcao2(); //f2

In this last example as the export is an object, you have to call the functions by doing call.funcao1() .

    
05.07.2018 / 20:56