在 Node.js 中,我如何“包含"?我的其他文件中的功能? [英] In Node.js, how do I "include" functions from my other files?

查看:11
本文介绍了在 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 中,我如何“包含"?我的其他文件中的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆