node.js - 在 Node Express 中的 js 文件中包含并分组相关函数

标签 node.js express

我有一个 Node Express 路由文件。它的与路由无关的函数数量变得越来越大 - 用于访问 Azure 和其他文件名相关函数的代码。

我相当确定我想在路由文件中保留路由函数(这里是 route/tally.js 文件,以及另一个文件中的文件名解析函数(即 fileName.jstallyAzure.js)。

  1. 如何告诉我的route.js 文件包含并引用另一个.js 文件中的所有函数。

    对于路由 js 文件,我尝试了 include("routes/tallyAzure.js");

  2. 解决方案中放置这些函数文件最合理的位置在哪里?我倾向于使用 routes 目录之外的目录。我应该注意哪些命名约定?

enter image description here

最佳答案

您需要使用exports 变量。以下是文档中的示例:http://nodejs.org/api/modules.html

circle.js:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

app.js:

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

关于node.js - 在 Node Express 中的 js 文件中包含并分组相关函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24620839/

相关文章:

node.js - NodeJS 域和expressjs

node.js - 访问 AzureBotStorage 中的所有用户数据

node.js - 使用带有 userID 的 Rest API 拉取用户数据

javascript - Mongodb,通过控制减少列表

javascript - 具有函数式编程(纯路由)的 Express.js 服务器

node.js - express.js 中 Ajax 请求的错误处理

node.js - Node.js模拟POST请求后如何访问response Body?

node.js - nodejs中fs.open()有什么用,fs.readfile和fs.open()有什么区别

node.js - nodejs .node-xmlhttprequest-sync-1 文件已创建

node.js - create-react-app + nodejs (express) 服务器