【问题标题】:Any way to include/require file in NodeJS like Python or PHP?有什么方法可以在 NodeJS 中包含/需要文件,比如 Python 或 PHP?
【发布时间】:2015-05-10 11:58:41
【问题描述】:

我在一个名为 util.js 的文件中定义了很多函数,我以函数 encode 为例。 使用时应该是这样的:

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

但我想直接使用encode,就像在PHP或Python中使用它一样:

include "util.php"
encode();

在NodeJS中有什么方法可以实现吗? 谢谢。

【问题讨论】:

标签: python node.js require


【解决方案1】:

是的,你可以这样做:

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

【讨论】:

    【解决方案2】:
    //utils.js
    decode = function(){
        console.log(222);
    }
    exports.wrap = function(g){
        g.encode = function(){}
    }
    
    //main.js
    require('./utils.js').wrap(global);
    encode();
    decode();
    

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 2018-11-17
      • 2018-05-26
      • 2019-08-15
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多