2

I defined many functions in a file called util.js, and I will take the function encode as an example. when using, it should be like this:

var util = require('./util.js');
util.encode();

but I want to use encode directly,just like using it in PHP or Python:

include "util.php"
encode();

Is there any way to achieve in NodeJS? Thanks.

friday
  • 31
  • 3
  • possible duplicate of [Load and execute external js file in node.js with access to local variables?](http://stackoverflow.com/questions/4481058/load-and-execute-external-js-file-in-node-js-with-access-to-local-variables) – Qantas 94 Heavy May 10 '15 at 12:34

2 Answers2

1

Yes, you can do it in this way:

var encode = require('./util.js').encode;
encode();
vanadium23
  • 3,516
  • 15
  • 27
1
//utils.js
decode = function(){
    console.log(222);
}
exports.wrap = function(g){
    g.encode = function(){}
}

//main.js
require('./utils.js').wrap(global);
encode();
decode();
BuffK
  • 1,189
  • 14
  • 17