假设我有一个叫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文件的基本导入。
要把“工具”变成一个模块,我一点也不觉得困难。尽管有其他的答案,我仍然建议使用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文件夹加载。
你可以只需要require('./filename')。
Eg.
// file: index.js
var express = require('express');
var app = express();
var child = require('./child');
app.use('/child', child);
app.get('/', function (req, res) {
res.send('parent');
});
app.listen(process.env.PORT, function () {
console.log('Example app listening on port '+process.env.PORT+'!');
});
// file: child.js
var express = require('express'),
child = express.Router();
console.log('child');
child.get('/child', function(req, res){
res.send('Child2');
});
child.get('/', function(req, res){
res.send('Child');
});
module.exports = child;
请注意:
你不能监听子文件的PORT,只有父express模块有PORT监听器
子正在使用“路由器”,而不是父Express moudle。
创建两个JavaScript文件。例如import_functions.js和main.js
1.) import_functions.js
// Declaration --------------------------------------
module.exports =
{
add,
subtract
// ...
}
// Implementation ----------------------------------
function add(x, y)
{
return x + y;
}
function subtract(x, y)
{
return x - y;
}
// ...
2.) main.js
// include ---------------------------------------
const sf= require("./import_functions.js")
// use -------------------------------------------
var x = sf.add(4,2);
console.log(x);
var y = sf.subtract(4,2);
console.log(y);
输出
6
2