Nodejs 共享相同的启动 class 到子路由
Nodejs sharing same initiated class to sub routes
我有一个这样的文件夹结构
.
├── 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;
.
我的文件夹结构是这样的,我正在尝试共享 System.test = 1 值定义在 /app.js 到 /routes/lemon/auth/index.js。
但我做不到,它总是 return null。
有没有共享同一个 class init 到子路由?
PS:我知道我的代码不对,我已经搜索了很多。英文资源一时看不懂,但真的搜了一下
这不起作用,因为 System.js
returns 是 class 而不是实例或对象。因此,当 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;
不是最优雅或可扩展的,但是;
global.System = new _System();
然后您可以在任何地方使用 System
。
我有一个这样的文件夹结构
.
├── 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;
.
我的文件夹结构是这样的,我正在尝试共享 System.test = 1 值定义在 /app.js 到 /routes/lemon/auth/index.js。 但我做不到,它总是 return null。
有没有共享同一个 class init 到子路由?
PS:我知道我的代码不对,我已经搜索了很多。英文资源一时看不懂,但真的搜了一下
这不起作用,因为 System.js
returns 是 class 而不是实例或对象。因此,当 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;
不是最优雅或可扩展的,但是;
global.System = new _System();
然后您可以在任何地方使用 System
。