In Node.js, how do I quot;includequot; functions from my other files?(在 Node.js 中,我如何“包含?我的其他文件中的功能?)
问题描述
假设我有一个名为 app.js 的文件.很简单:
Let's say I have a file called app.js. Pretty simple:
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 中使用?
What if I have a functions inside "tools.js". How would I import them to use in apps.js?
或者...我应该把工具"变成一个模块,然后需要它吗?<<看起来很难,我宁愿做 tools.js 文件的基本导入.
Or...am I supposed to turn "tools" into a module, and then require it? << seems hard, I rather do the basic import of the tools.js file.
推荐答案
你可以 require 任何 js 文件,你只需要声明你想要暴露的内容.
You can require any js file, you just need to declare what you want to expose.
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
在你的应用文件中:
// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined
这篇关于在 Node.js 中,我如何“包含"?我的其他文件中的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Node.js 中,我如何“包含"?我的其他文件中


基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01