Javascript 在 node.js 中加载和执行外部 js 文件并访问局部变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4481058/
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-08-23 12:35:53  来源:igfitidea点击:

Load and execute external js file in node.js with access to local variables?

javascriptnode.js

提问by Travis

Is it easy/possible to do a simple include('./path/to/file')type of command in node.js?

include('./path/to/file')在 node.js 中执行简单类型的命令是否容易/可能?

All I want to do is have access to local variables and run a script. How do people typically organize node.js projects that are bigger than a simple hello world? (A fully functional dynamic website)

我想要做的就是访问局部变量并运行脚本。人们通常如何组织比简单的 hello world 更大的 node.js 项目?(一个功能齐全的动态网站)

For example I'd like to have directories like:

例如,我想要目录如下:

/models

/models

/views

/views

... etc

... 等等

回答by Shripad Krishna

Just do a require('./yourfile.js');

做一个 require('./yourfile.js');

Declare all the variables that you want outside access as global variables. So instead of

将您希望外部访问的所有变量声明为全局变量。所以代替

var a = "hello"it will be

var a = "hello"这将是

GLOBAL.a="hello"or just

GLOBAL.a="hello"要不就

a = "hello"

a = "hello"

This is obviously bad. You don't want to be polluting the global scope. Instead the suggest method is to exportyour functions/variables.

这显然很糟糕。您不想污染全局范围。相反,建议方法是针对export您的函数/变量。

If you want the MVC pattern take a look at Geddy.

如果您想要 MVC 模式,请查看 Geddy。

回答by Ivan Torres

You need to understand CommonJS, which is a pattern to define modules. You shouldn't abuse GLOBAL scope that's always a bad thing to do, instead you can use the 'exports' token, like this:

你需要了解 CommonJS,这是一种定义模块的模式。你不应该滥用 GLOBAL 范围,这总是一件坏事,相反,你可以使用 'exports' 标记,如下所示:

// circle.js

var PI = 3.14; // PI will not be accessible from outside this module

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

And the client code that will use our module:

以及将使用我们模块的客户端代码:

// client.js

var circle = require('./circle');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

This code was extracted from node.js documentation API:

此代码是从 node.js 文档 API 中提取的:

http://nodejs.org/docs/v0.3.2/api/modules.html

http://nodejs.org/docs/v0.3.2/api/modules.html

Also, if you want to use something like Rails or Sinatra, I recommend Express (I couldn't post the URL, shame on Stack Overflow!)

另外,如果你想使用 Rails 或 Sinatra 之类的东西,我推荐 Express(我无法发布 URL,对 Stack Overflow 感到羞耻!)

回答by David Wolever

If you are writing code for Node, using Node modules as described by Ivan is without a doubt the way to go.

如果您正在为 Node 编写代码,那么使用 Ivan 描述的 Node 模块毫无疑问是要走的路。

However, if you need to load JavaScript that has already been written and isn't aware of node, the vmmodule is the way to go (and definitely preferable to eval).

但是,如果您需要加载已经编写vm好的JavaScript 并且不知道 node,那么模块是要走的路(绝对比 更可取eval)。

For example, here is my execfilemodule, which evaluates the script at pathin either contextor the global context:

例如,这是我的execfile模块,它path在任一context或全局上下文中评估脚本:

var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
  var data = fs.readFileSync(path);
  vm.runInNewContext(data, context, path);
}

Also note: modules loaded with require(…)don't have access to the global context.

另请注意:加载的模块require(…)无权访问全局上下文。

回答by Rox

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

如果您计划加载外部 javascript 文件的函数或对象,请使用以下代码在此上下文中加载 - 请注意 runInThisContext 方法:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

回答by Jonathan Benn

Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.exportfunctionality.

扩展@Shripad@Ivan的答案,我建议您使用 Node.js 的标准module.export功能。

In your file for constants (e.g.constants.js), you'd write constants like this:

在您的常量文件(例如constants.js)中,您可以像这样编写常量:

const CONST1 = 1;
module.exports.CONST1 = CONST1;

const CONST2 = 2;
module.exports.CONST2 = CONST2;

Then in the file in which you want to usethose constants, write the following code:

然后在要使用这些常量的文件中,编写以下代码:

const {CONST1 , CONST2} = require('./constants.js');

If you've never seen the const { ... }syntax before: that's destructuring assignment.

如果您以前从未见过const { ... }语法:那就是解构赋值

回答by lupu51nfactum N778

Sorry for resurrection. You could use child_process module to execute external js files in node.js

对不起复活。您可以使用 child_process 模块在 node.js 中执行外部 js 文件

var child_process = require('child_process');

//EXECUTE yourExternalJsFile.js
child_process.exec('node yourExternalJsFile.js', (error, stdout, stderr) => {
    console.log(`${stdout}`);
    console.log(`${stderr}`);
    if (error !== null) {
        console.log(`exec error: ${error}`);
    }
});