【问题标题】:Nodejs sharing same initiated class to sub routesNodejs将相同的启动类共享给子路由
【发布时间】:2019-01-31 17:17:05
【问题描述】:

我有一个这样的文件夹结构

.
├── models
│   └── System.js
└── src
    ├── app.js
    ├── index.js
    └── routes
        ├── lemon
        │   ├── auth
        │   │   └── index.js
        │   └── index.js
        └── index.js

.

/models/System.js

class System {
    constructor() {
        this.test = null;
    }
}

module.exports = System

.

/src/app.js

const express = require("express");
const _System = require("../models/System");

const app = express();

var System = new _System();
System.test = 1;

//..... other codes

.

/src/routes/lemon/auth/index.js

const express = require("express");
const _System = require("../../../../models/System");

const router = express.Router();

console.log(_System.test); //returns null

router.get('/', (req, res) => {
    res.send("Hello World");
});

module.exports = router;

.

我的文件夹结构是这样的,我正在尝试将 /app.js 中定义的 System.test = 1 值共享给 /routes/柠檬/auth/index.js。 但我做不到,它总是返回 null。

有没有办法与子路由共享同一个类初始化?

PS:我知道我的代码不正确,我已经搜索了很多。暂时看不懂英文资源太多了,但是我真的去搜了。

【问题讨论】:

    标签: node.js class inheritance subclass


    【解决方案1】:

    不是最优雅或可扩展的,但是;

    global.System =  new _System();
    

    然后您可以在任何地方使用System

    【讨论】:

    • 在我找到更好的解决方案之前,您的解决方案是最好的!谢谢@RussFreeman
    【解决方案2】:

    这不起作用,因为System.js 返回一个类而不是实例或对象。所以当var System = new _System(); System.test = 1;app.js中执行时,实例是应用模块本地的,不与路由共享。

    如果你想在不同的模块之间共享某种配置文件,你可以将你的 System 模块定义为一个简单的对象:

    'use strict' // <-- this is good practice to be more rigoreous
    
    const System = {
        test: 1
    };
    
    module.exports = System;
    

    【讨论】:

    • test 变量只是一个示例。我需要做的是,在任何地方使用 System=new _System() 。一旦我启动了系统,我需要能够在最深的路由文件中使用它
    猜你喜欢
    • 2019-04-10
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多