假设我有一个叫app。js的文件。很简单:
var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('index', {locals: {
title: 'NowJS + Express Example'
}});
});
app.listen(8080);
如果我在“tools.js”中有一个函数。我如何将它们导入到apps.js中使用?
还是……我应该把“工具”变成一个模块,然后需要它吗?<<似乎很难,我宁愿做tools.js文件的基本导入。
包含文件并在给定的(非全局)上下文中运行它
fileToInclude.js
define({
"data": "XYZ"
});
main.js
var fs = require("fs");
var vm = require("vm");
function include(path, context) {
var code = fs.readFileSync(path, 'utf-8');
vm.runInContext(code, vm.createContext(context));
}
// Include file
var customContext = {
"define": function (data) {
console.log(data);
}
};
include('./fileToInclude.js', customContext);
它与我的工作如下....
Lib1.js
//Any other private code here
// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};
// Again any private code
现在在Main.js文件中,你需要包含Lib1.js
var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);
请记住将Lib1.js放在node_modules文件夹中。
要把“工具”变成一个模块,我一点也不觉得困难。尽管有其他的答案,我仍然建议使用module.exports:
//util.js
module.exports = {
myFunction: function () {
// your logic in here
let message = "I am message from myFunction";
return message;
}
}
现在我们需要将这个exports分配到全局作用域(在你的应用程序|index|server.js中)
var util = require('./util');
现在你可以引用和调用函数为:
//util.myFunction();
console.log(util.myFunction()); // prints in console :I am message from myFunction
我只是想补充一点,如果你只需要从你的tools.js中导入某些函数,那么你可以使用解构赋值,这在node.js版本6.4中得到了支持-参见node.green。
例子:
(两个文件在同一个文件夹中)
tools.js
module.exports = {
sum: function(a,b) {
return a + b;
},
isEven: function(a) {
return a % 2 == 0;
}
};
main.js
const { isEven } = require('./tools.js');
console.log(isEven(10));
输出:真正的
这也避免了你将这些函数赋值为另一个对象的属性,就像下面(常见)赋值的情况一样:
Const tools = require('./tools.js');
你需要调用tools.isEven(10)。
注意:
不要忘记在文件名前面加上正确的路径——即使两个文件在同一个文件夹中,也需要加上。/前缀
来自Node.js文档:
没有前导'/','。/',或'../'表示一个文件,模块
必须是核心模块或从node_modules文件夹加载。