[英]How to realy include a js file in Node.js
我没有在Google上找到任何真正可行的解决方案,所以...
有一个名为vm
的模块,但是人们说它很重。 我需要一些简单的功能,例如PHP的include
,其功能类似于将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
也是一个坏主意...
还有其他解决方案吗?
对每个文件使用require和module.exports也是一个坏主意...
不, require
是您在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.
您试图做的事情破坏了模块性,并违反了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
调用中从磁盘读取。 没有布宜诺斯艾利斯。
您不需要将每个变量附加到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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.