Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require to global scope in node.js

In my node.js script I have:

var wu = require('./wu-0.1.8.js');

just to play with wu.

If it was in browser, then I could just use wu everywhere e.g.

wu([1,2,3]).map( function(n){ return n*n; } );

Hovever in node.js I have to write:

wu.wu([1,2,3]).map( function(n){ return n*n; } );

Is it possible to append wu to global scope so that I dont have to type wu.wu all the time?

like image 827
Sir Bohumil Avatar asked Dec 22 '25 05:12

Sir Bohumil


2 Answers

var wu = require('./wu-0.1.8.js').wu;

edit (response to comments):

If you need to use other methods in require('./wu-0.1.8.js'), you can always do this...

var wuModule = require('./wu-0.1.8.js'); 
var wu = wuModule.wu;

// Now you can do 

wu([1,2,3]).map( function(n){ return n*n; } );
wuModule.someOtherWuMethod(...);
like image 189
AlexMA Avatar answered Dec 23 '25 19:12

AlexMA


Well, I suggest you not to do so but you can iterate through the wu object properties and attach them to global object:

var _wu = require('./wu-0.1.8.js');
var key;
for (key in _wu) {
  if (_wu.hasOwnProperty(key)) {
    global[key] = _wu[key];
  }
}
like image 31
fardjad Avatar answered Dec 23 '25 17:12

fardjad