Import functions from another file (Node.js)

Asked

Viewed 4,180 times

1

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()]. It would be possible to "import" these functions into the bot.js and only use add() to it instead of having to write the function in the bot.js file itself?

1 answer

2

Can always do require of the file in question to be able to use what it has, provided that it has made the necessary exports in it.

In the Somar.js could make the whole function export, using module.exports:

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

Then in the bot.js would require to use:

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

Note that in the require you need to indicate the path to the file. As they are in the same folder just prefix with ./. It is also important to mention that the require does not take the file extension.

You can also export more than one function if you change the way you export. By way of example we assume that in Call.js wanted 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 doing call.funcao1().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.