Using Classes in Node -
Here we are requiring the ReadWrite module and calling a makeObject(), which returns the object of the ReadWrite class. Which we are using to call the methods. index.js
const ReadWrite = require('./ReadWrite').makeObject();
const express = require('express');
const app = express();
class Start {
constructor() {
const server = app.listen(8081),
host = server.address().address,
port = server.address().port
console.log("Example app listening at http://%s:%s", host, port);
console.log('Running');
}
async route(req, res, next) {
const result = await ReadWrite.readWrite();
res.send(result);
}
}
const obj1 = new Start();
app.get('/', obj1.route);
module.exports = Start;
ReadWrite.js
Here we making a makeObject method, which makes sure that a object is returned, only if a object is not available.
class ReadWrite {
constructor() {
console.log('Read Write');
this.x;
}
static makeObject() {
if (!this.x) {
this.x = new ReadWrite();
}
return this.x;
}
read(){
return "read"
}
write(){
return "write"
}
async readWrite() {
try {
const obj = ReadWrite.makeObject();
const result = await Promise.all([ obj.read(), obj.write()])
console.log(result);
check();
return result
}
catch(err) {
console.log(err);
}
}
}
module.exports = ReadWrite;
For more explanation go to https://medium.com/@nynptel/node-js-boiler-plate-code-using-singleton-classes-5b479e513f74