在 node.js 中加载并执行具有本地变量访问权限的外部 js 文件?

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

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

例如,我希望有这样的目录:

/models

/views

等等

233286 次浏览

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

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

会的

GLOBAL.a="hello"或者只是

a = "hello"

这显然是不好的。你不想污染全球范围。 相反,建议的方法是对 export你的函数/变量。

如果你想要 MVC 模式,看看盖迪。

您需要理解 CommonJS,它是一种定义模块的模式。你不应该滥用 GLOBAL 范围,这总是一件坏事,相反,你可以使用“导出”标记,像这样:

// 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模块(而且肯定优于 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 的标准 模块,出口功能。

在你的常量文件(例如:。 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}`);
}
});