Nodejs sharing same initiated class to sub routes
Nodejs sharing same initiated class to sub routes
I have a folder structer like this
.
├── 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;
.
My folder structer is like this and I'm trying to share the System.test = 1 value defined at /app.js to /routes/lemon/auth/index.js.
But I couldn't able to do that and it always return null.
Is there anyway to share the same class init to sub routes?
PS: I know that my code isn't right and I've searched a lot. I can't understand English resources too much at the moment but I really searched up for it.
2 Answers
2
This doesnt work because System.js
returns a class and not an instance or an object. So when var System = new _System(); System.test = 1;
is exectued in app.js
, the instance is local to the app module and not shared with the route.
System.js
var System = new _System(); System.test = 1;
app.js
If you want to share some kind of a config file between different modules, you can define your System
module as a simple object:
System
'use strict' // <-- this is good practice to be more rigoreous
const System =
test: 1
;
module.exports = System;
Not the most elegant or scalable but;
global.System = new _System();
You can then use System
anywhere.
System
Till I found a more good solution, your solution is the best! Thanks @RussFreeman
– SeahinDeniz
Aug 25 at 17:05
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
The test variable is just an example. What I need to do is, use the System=new _System() anywhere. Once I initiated the System, I'll need able to use it in the deepest route file
– SeahinDeniz
Aug 25 at 17:08