繁体   English   中英

在node.js中加载并执行外部js文件,可以访问局部变量吗?

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

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

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

例如,我想要有以下目录:

/models

/views

......等

只需要一个require('./yourfile.js');

将您想要外部访问的所有变量声明为全局变量。 而不是

var a = "hello"它会

GLOBAL.a="hello"或只是

a = "hello"

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

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

您需要了解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;
};

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

// client.js

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

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

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

此外,如果你想使用像Rails或Sinatra这样的东西,我建议使用Express(我无法发布URL,耻辱Stack Overflow!)

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

但是,如果您需要加载已经编写但不知道节点的JavaScript,那么vm模块就是vm的方式(并且绝对优于eval )。

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

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

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

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

在您的常量文件( 例如 constants.js )中,您将编写如下常量:

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

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

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

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

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

如果您计划加载外部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. 

抱歉复活。 您可以使用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}`);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM