friday
friday

Reputation: 31

Any way to include/require file in NodeJS like Python or PHP?

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.

Upvotes: 2

Views: 1282

Answers (2)

BuffK
BuffK

Reputation: 1396

//utils.js
decode = function(){
    console.log(222);
}
exports.wrap = function(g){
    g.encode = function(){}
}

//main.js
require('./utils.js').wrap(global);
encode();
decode();

Upvotes: 1

vanadium23
vanadium23

Reputation: 3586

Yes, you can do it in this way:

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

Upvotes: 1

Related Questions