Muhammad Umar
Muhammad Umar

Reputation: 11782

Calling function and variables from other files in node.js

I have two files

app.js and funcs.js

in app.js i have following code

require('./funcs.js');

in funcs.js i have following code

var TYPE_KEEPER = 1;
var TYPE_USER   = 0;

function getBooking(bookingId, callback)
{   
   // some function here.
}

Now when i run app.js, and call TYEP_KEEPER, It gives me error

ReferenceError: TYPE_DRIVER is not defined

How can i define all constants in other function. and also how can i call the function in app.js , the very function defined in funcs.js

Upvotes: 0

Views: 64

Answers (1)

skypjack
skypjack

Reputation: 50550

Here a possible solution to your problem, even though it is not the only one available (as an example, you could export a factory of objects in place of what is below).

In the first file, you have to export your stuff as it follows:

module.exports = {
    "TYPE_KEEPER": 1,
    "TYPE_USER": 0,
    "getBooking": function (bookingId, callback) { /* some function here. */ }
}

Somewhere, you can use them as it follows:

var stuff = require('path_to_the_file_above');
console.log(stuff["TYPE_KEEPER"]);
stuff.getBooking();

Upvotes: 2

Related Questions