var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
var data = fs.readFileSync(path);
vm.runInNewContext(data, context, path);
}
// 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));
4 回答
如果您正在为Node编写代码,那么使用Ivan所描述的Node模块毫无疑问是要走的路 .
但是,如果您需要加载已经编写但不知道节点的JavaScript,那么vm模块就是可行的方式(并且绝对优于
eval
) .例如,这是我的
execfile
模块,它在context
或全局上下文中评估path
处的脚本:另请注意:使用
require(…)
加载的模块无权访问全局上下文 .做一个
require('./yourfile.js');
将您想要外部访问的所有变量声明为全局变量 . 而不是
var a = "hello"
会的GLOBAL.a="hello"
或只是a = "hello"
这显然很糟糕 . 您不希望污染全球范围 . 相反,建议方法是
export
您的函数/变量 .如果你想要MVC模式,请看看Geddy .
您需要了解CommonJS,它是一种定义模块的模式 . 你不应该滥用GLOBAL范围,这总是一件坏事,而是你可以使用'exports'标记,如下所示:
以及将使用我们模块的客户端代码:
此代码是从node.js文档API中提取的:
http://nodejs.org/docs/v0.3.2/api/modules.html
另外,如果你想使用像Rails或Sinatra这样的东西,我建议使用Express(我无法发布URL,耻辱Stack Overflow!)
扩展@Shripad和@Ivan 's answer, I would recommend that you use Node.js'的标准module.export功能 .
在你的常量文件中(例如
constants.js
),你要写这样的常量:然后在要使用这些常量的文件中,编写以下代码:
如果您之前从未见过
const { ... }
语法:那是destructuring assignment .