我没有在Google上找到任何真正解决此问题的解决方案,所以......
有一个名为vm
的模块,但人们说它很重。我需要一些简单的函数,比如PHP的include
,它就像包含文件的代码一样,直接插入到你需要的代码中,然后执行。
我试图创建这样的功能
function include(path) {
eval( fs.readFileSync(path) + "" );
}
但它并不那么简单......如果我在示例中向您展示原因,那就更好了。
假设我需要包含带内容的 file.js 文件
var a = 1;
相对文件看起来像这样
include("file.js");
console.log(a); // undefined
正如您已经意识到a
未定义,因为它不是从函数继承的。
似乎唯一的方法就是输入这个令人毛骨悚然的代码
eval( fs.readFileSync("file.js") + "" );
console.log(a); // 1
每次都没有包装函数,以便从文件中获取所有功能。
对每个文件使用require
和module.exports
也是一个坏主意......
还有其他解决方案吗?
答案 0 :(得分:7)
对每个文件使用require with module.exports也是一个坏主意......
不,require
is 在NodeJS中执行此操作的方式:
var stuff = require("stuff");
// Or
var stuff = require("./stuff"); // If it's within the same directory, part of a package
将你的大vm
分成小的,可维护的部分,如果他们需要聚集成一个大而不是直接使用,有一个vm.js
那样做。
所以例如
stuff.js
:
exports.nifty = nifty;
function nifty() {
console.log("I do nifty stuff");
}
morestuff.js
:
// This is to address your variables question
exports.unavoidable = "I'm something that absolutely has to be exposed outside the module.";
exports.spiffy = spiffy;
function spiffy() {
console.log("I do spiffy stuff");
}
vm.js
:
var stuff = require("./stuff"),
morestuff = require("./morestuff");
exports.cool = cool;
function cool() {
console.log("I do cool stuff, using the nifty function and the spiffy function");
stuff.nifty();
morestuff.spiffy();
console.log("I also use this from morestuff: " + morestuff.unavoidable);
}
app.js
(使用vm
的应用):
var vm = require("./vm");
vm.cool();
输出:
I do cool stuff, using the nifty function and the spiffy function I do nifty stuff I do spiffy stuff I also use this from morestuff: I'm something that absolutely has to be exposed outside the module.
答案 1 :(得分:0)
您要做的是打破模块化并违反Node.js最佳做法。
假设你有这个模块(sync-read.js):
var fs = require('fs');
module.exports = {
a: fs.readFileSync('./a.json'),
b: fs.readFileSync('./b.json'),
c: fs.readFileSync('./c.json')
}
第一次调用模块时......
var data = require('./sync-read');
...它将被缓存,您不会再次从磁盘读取这些文件。使用您的方法,您将在每次include
呼叫时从磁盘读取。没有bueno。
您无需将每个变量附加到module.exports
(如上面的评论):
var constants = {
lebowski: 'Jeff Bridges',
neo: 'Keanu Reeves',
bourne: 'Matt Damon'
};
function theDude() { return constants.lebowski; };
function theOne() { return constants.neo; };
function theOnly() { return constants.bourne; };
module.exports = {
names: constants,
theDude : theDude,
theOne : theOne
// bourne is not exposed
}
然后:
var characters = require('./characters');
console.log(characters.names);
characters.theDude();
characters.theOne();