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;





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



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế