javascript node.js:从另一个模块访问局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14020189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:30:28  来源:igfitidea点击:

node.js: Accessing local variables from another module

javascriptnode.jsserverside-javascriptnode-modules

提问by fridojet

My Problem

我的问题

I'm writing a nodemodule called a, which require()s a module b(written by a stranger). Unfortunately, adoesn't only need to access the public members - it also needs to access local variables declared in the scope of the module.

我正在编写一个node名为的模块a,它require()是一个模块b(由陌生人编写)。不幸的是,a它不仅需要访问公共成员——它还需要访问在模块范围内声明的局部变量。

// a
var b = require('b');

console.log(b.public);
console.log(b.private); // undefined


// b
var c = require('c');
var stdin = process.stdin;

exports.public = true;
var private = true;

My Solution

我的解决方案

// a
var b = require('b');
var srcPath = require.resolve('b');

console.log(b.public);
fs.readFile(srcPath, 'utf-8', function (err, src) {
    var box = {};
    var res = vm.runInNewContext(src, box, srcPath);
    console.log(box.private);
});

But vmdoesn't run bas a module, so require()etc. aren't accessible from the context of the vm. So there are ReferenceErrors like:

vmb作为模块运行,因此require()无法从vm. 所以有ReferenceError像:

    var res = vm.runInNewContext(src, box, scPath);
                 ^
ReferenceError: require is not defined
    at <module b>
    at <module a>
    at fs.readFile (fs.js:176:14)
    at Object.oncomplete (fs.js:297:15)

My Question

我的问题

Which is the cleanest way to get the value of a local variable declared in another module? Ideas?

获取在另一个模块中声明的局部变量的值的最简洁方法是什么?想法?

Thanks for your help.

谢谢你的帮助。

回答by Moritz

you should probably mostly never have to do this, but there might be reasons.

您可能应该永远不必这样做,但可能是有原因的。

you can hook the loader and inject javascript code to export what you want.

您可以挂钩加载程序并注入 javascript 代码以导出您想要的内容。

// let's say you have node_modules/foreignmodule/index.js
// and in that script there is a local (not-exported) function foreignfunction().

var path = require('path');
_oldLoader = require.extensions['.js'];
require.extensions['.js'] = function(mod, filename) {
    if (filename == path.resolve(path.dirname(module.filename), 'node_modules/foreignmodule/index.js')) {
        var content = require('fs').readFileSync(filename, 'utf8');
        content += "module.exports.foreignfunction=foreignfunction;\n";
        mod._compile(content, filename);
    } else {
        _oldLoader(mod, filename);
    }
};

require('foreignmodule').foreignfunction();

回答by AlexOwl

Check out my module import-locals

查看我的模块import-locals

const patcher = new Patcher();
patcher.export("yourmodule", "Foo");
const { Foo } = require("yourmodule");

回答by ma?ek

Just exportthe values properly

只是export正确的值

Module B

模块 B

// b.js

// some local var
var foo = 'Bar';

exports.Foo = foo;
exports.Hello = 'World';

Module A

模块 A

// a .js
b = require('./b');
console.log(b.Foo); //=> 'Bar'
console.log(b.Hello); // => 'World'


Read more about nodejs module.exportshere

在此处阅读有关nodejs module.exports 的更多信息