Pablo DelaNoche
Pablo DelaNoche

Reputation: 677

Separate functions in node.js file

I want to separate functions in my node.js file. I don't know how to do it.

Here is an example:

    var var1 = 'I want to use this var along across all included files';
    var var2 = 'I want to use this var along across all included files';
    var actions = {
        send1() { //function 1 with var1 & var2 },
        send1a() { //function 1a with var1 & var2},
        send2() { //function 2 with var1 & var2},
        send2a() { //function 2a with var1 & var2}
    };

I want to export send1() & send1a() in function1.js and send2() & send2a() in function2.js in order to have clean files and use var1 & var2.

How can I do that correctly?

Upvotes: 2

Views: 2097

Answers (2)

Priyesh Kumar
Priyesh Kumar

Reputation: 2857

Create 2 module files: fun1.js

var var1 = "CONSTANT"


var actions = {
    // Whatever you want to export, you can write it here
    send1: function () {
        console.log("send1", var1)
    },
    send1a: function () {
        console.log("send1a")
    },
    a: "asdsad",
    b: 45,
    c: [1, 2, 3, 4, 5, 6],
    var1: var1
}


module.exports = actions

/*
 Or you can export using
 module.exports = {
     actions: actions,
     variableX: "something"
 }

 then in other modules, import it as
 var fun = require('./module_path')

 And use it as fun.variableX, fun.actions.send1 etc
 */

fun2.js

// Import variable from other module
var fun1 = require('./fun1')
// or just import var1
// var var1 = require('./fun1').var1

var actions = {
    send2: function () {
        console.log("send2", fun1.var1)
    },
    send2a: function () {
        console.log("send2a")
    }
}


module.exports = actions

Then in main file

main.js

// Import all modules
var fun1 = require('./fun1')
var fun2 = require('./fun2')

console.log(fun1.a) // Prints array

// fun1 will have all exported modules from fun1.js file
fun1.send1() // Prints send1 CONSTANT
fun1.send1a()

// fun2 will have all exported modules from fun2.js file
fun2.send2()  // Prints send2 CONSTANT
fun2.send2a()

Upvotes: 2

Lix
Lix

Reputation: 48006

What you would want to do is have an object containing all of your functions along side their "names" as the keys -
You don't actually need the keys to be wrapped in quotes - I have done it here just for clarity.

var functions1 = require('./function1')
var functions2 = require('./function2')

var actions = {
    'send1':  functions1.send1
    'send1a': functions2.send1a
    ...
};

module.exports.actions = actions;

To call the functions via the actions object, all you would need to do is something like this -

var actionToDo = 'send1'; // key value that holds the function.
actions[actionToDo]() // here is the actual call to the `send1()` function from the `functions1,js` module.

Upvotes: 1

Related Questions