javascript - 向下传递模块 - javascript
问题描述
我有这样的结构:
-controllers
-matches
-index.js
-create.js
-get.js
在索引中,我像这样导出其他模块:
const get = require("./get");
const create = require("./create");
module.exports = {
get,
create,
}
获取示例:
const MatchModel = require("../../models/Match");
const get = async (req, res, next) => {
let matches = await MatchModel.find();
console.log(matches);
};
module.exports = get;
现在既然 get 和 create 共享同一个模块(MatchModel),有没有办法将它传递下来,而不是在每个文件中都导入它?
我想做的是这样的:索引:
const MatchModel = require("../../models/Match");
const get = require("./get");
const create = require("./create");
module.exports = {
get,
create,
}
获取示例:
const get = async (req, res, next) => {
let matches = await MatchModel.find();
console.log(matches);
};
module.exports = get;
我正在使用猫鼬作为架构。
解决方案
在您的 index.js 或 app.js 中,导出快速应用程序的脚本文件添加
global_get = require("../get"); // with the path according to your structure
没有标识符
标识符,如const、let或var。
现在您基本上可以在您的 nodejs 应用程序中的任何位置调用此模块/函数,例如:
let result = await global.global_get();
如果您有一系列导出功能,则:
let result = await global.global_get.some_function();
在这里,global或GLOBAL (depreciated) 标识整个 nodejs 应用程序中的全局变量。
但是,我建议您在需要的地方导入/需要模块
推荐阅读
- python - 为什么 `await coro()` 会阻塞而 `await task` 不会?
- python - Django Oauth Toolkit 作为 SSO 服务器
- javascript - 对象作为 React 子对象无效(找到:带键的对象...)
- algorithm - 如果给定优先级队列,如何绘制 Gnatt 图并计算调度算法的到达和等待时间?
- javascript - 如何停止循环文本动画
- javascript - Typescript - 键入一个接受数组的函数,更改其属性之一,但仍返回相同的类型化数组
- c++ - 如何进行无分支数字循环?
- c++ - QGridLayout 小部件设置相等大小
- sql - 如果 count(column) 然后在 Oracle 中选择
- c# - 在 Cefsharp.WPF 中,我应该如何对“fi-FI”(芬兰语)语言进行拼写检查?