MagisterMundus MagisterMundus - 1 month ago 6
Node.js Question

NodeJS - Import functions from other file and use as if it had them before?

Let's say I have a file called

server.js
:

//server.js
var net = require('net');
var server = net.createServer(function (socket){
socket.on('data',function(data){
console.log("Received: "+data);
});
});


And another file called
functions.js
:

//functions.js
module.exports = {
test: function () {
// do something
},
other: function () {
// do something
}
};


I know I can do something like this:

var functions = require('./functions');
functions.test();


But I really wanted to be able to use the function directly, like this:

require('./functions');
test();


Any suggestions?

Answer

While you could load them into the global variable, another possible, and perhaps more sane* way to do that would be to assign the method to the variable test.

var test = require('./functions').test;
var functions = require('./functions');
var test2 = functions.test;

* = I say sane, because touching the global scope can have some unexpected results, cuts down on general readability, (Hey, where did this test variable come from? I didn't see it defined anywhere in the code.), and worst case scenario, you might run into name clashes, or even overwrite something you need in the global scope. Not to say that loading some things into the global scope isn't a good idea, or even downright useful, but often times, it's best to keep things scoped locally for readability.

An article on touching the global scope in the browser.

Comments