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 中,我如何“包含"?我的其他文件中


- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01