【问题标题】:Node.js: Require localsNode.js:需要本地人
【发布时间】:2012-05-02 19:35:53
【问题描述】:

我想要什么

是否可以将本地变量传递给所需的模块? 例如:

// in main.js
var words = { a: 'hello', b:'world'};
require('module.js', words);

// in module.js
console.log(words.a + ' ' + words.b) // --> Hello World

我问这个是因为在 PHP 中,当您需要或包含时,包含另一个文件的文件会继承它的变量,这在某些情况下非常有用,如果这也可以在 node.js 中完成,我会很高兴.

我尝试过但没有成功

 var words = { a: 'hello', b:'world'};
 require('module.js', words);

 var words = { a: 'hello', b:'world'};
 require('module.js');

当在module.js 中调用words 时,这两者都会给出ReferenceError: words is not defined

那么没有全局变量就可以吗?

【问题讨论】:

    标签: node.js module require locals


    【解决方案1】:

    问题是:你想达到什么目标?

    如果您只想导出静态函数,可以使用the answer from tehlulz。如果您想在 exports 属性中存储一个对象并从需要缓存中受益,node.js 提供的(脏)方法将是全局变量。我想这就是你尝试过的。

    在 Web 浏览器上下文中使用 JavaScript,您可以使用 window 对象来存储全局值。 Node 只为所有模块提供了一个全局对象:process 对象:

    main.js

    process.mysettings = { a : 5, b : 6};
    var mod = require(mymod);
    

    mymod.js

    module.exports = { a : process.mysettings.a, b : process.mysettings.b, c : 7};
    

    或者,如果您对导出缓存不感兴趣,您可以这样做:

    main.js

    var obj = require(mymod)(5,6);
    

    mymod.js

    module.exports = function(a,b){
     return { a : a, b : b, c : 7, d : function(){return "whatever";}};
    };
    

    【讨论】:

    • "So is it possible at all without global variables?"
    【解决方案2】:

    您要做的是使用参数导出它,以便您可以将变量传递给它。

    module.js

    module.exports = function(words){
        console.log(words.a + ' ' + words.b);
    };
    

    main.js

    var words = { a: 'hello', b:'world'};
    // Pass the words object to module
    require('module')(words);
    

    你也可以在 require 中去掉 .js :)

    【讨论】:

    • 这应该可以,但它有点脏:\没有module.exports函数是不是不可能?
    • 不幸的是,我不知道。我希望有人提供一种更简洁的方法,但我对 require 的理解是一切都作为模块工作。因此,当您需要一个函数时,要在模块外部使用,您必须将其“导出”到应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2012-05-15
    • 2022-01-07
    • 2013-03-03
    • 2013-11-10
    • 2015-02-21
    相关资源
    最近更新 更多