1

I have a class that executes CRUD operations in my NodeJS app. It is designed to queue operations and execute them sequentially. As of now, I am using this class in multiple other files, and as a result, there are multiple instances of it, each with their own separate queue.

My goal is to be able to share the same queue across all other modules without having multiple instances, so that all of the CRUD operations are sequentially executed in the order they are called.

//SomeFile.js
var data = new CRUDQueue();
data.addRecord(someRecord); //Pushes an add operation to the internal queue

//SomeOtherFile.js
var data = new CRUDQueue();
data.deleteRecord(someRecord); //Pushes a delete operation to the internal queue

Is there a way I can share the same CRUDQueue object across both of these files? Preferably without using global or passing it to the constructor?

1 Answer 1

5

Since NodeJS has modules caching, same instance of the object is returned every time you import by using require. But the trick is you have to export the instance instead of the class.

Here's an example:

crude-queue.js

class CRUDQueue {

    constructor (){
        console.log('constructor called'); // will print only once
        this.list = [];
    }

    addRecord (item){
        this.list.push(item);
    }

    deleteRecord (key) {
        var index = this.list.indexOf(key);
        if(index > -1){
            this.list.splice(index, 1);
        }
    }
}

var q = new CRUDQueue(); // this is crucial, one instance is created and cached by Node
module.exports = q;

main.js

var crudQueue = require('./crud-queue');
crudQueue.addRecord('apple');
crudQueue.addRecord('banana');

some-other-file.js

var sameInstanceOfCrudQueue = require('crud-queue');
sameInstanceOfCrudQueue.deleteRecord('apple');

yet-another-file.js

var thirdImportQueue = require('crud-queue');
console.log(thirdImportQueue); // prints ['banana']

From above, we can see that same instance of CRUDQueue is being used while performing operations on different files.

Sign up to request clarification or add additional context in comments.

1 Comment

this solution will not work if constructor have parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.