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


基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01