Reputation: 22113
I am learning redis with Node.js to implement the Queue system
with file "producer_worker.js"
// producer_worker.js
var redis = require("redis")
var client = redis.createClient();
var queue = require("./queue");
var logsQueue = new queue.Queue("logs", client);
var MAX = 5;
for (var i = 0;i < MAX; i++) {
logsQueue.push("Hello world #" + i);
}
console.log("Created " + MAX + " logs");
client.quit();
and "queue.js"
function Queue(queueName, redisClient) {
this.queueName = queueName;
this.redisClient = redisClient;
this.queueKey = "queues:" + queueName;
this.timeout = 0;
Queue.prototype.size = function (callback) {
this.redisClient.llen(this.queueKey, callback);
};
Queue.prototype.push = function(data) {
this.redisClient.lpush(this.queueKey, data);
};
Queue.prototype.pop = function(callback) {
this.redisClient.brpop(this.queueKey, this.timeout, callback);
};
exports.Queue = Queue;
}
It generates error when I tried to run it :
node producer_worker.js
var logsQueue = new queue.Queue("logs", client)
TypeError: queue.Queue is not a constructor
I have checked multiple times to ensure my codes consistent with those of book.
How could I fix the TypeError?
Upvotes: 0
Views: 3152
Reputation: 4615
You have to pull off some of your code from function scope:
function Queue(queueName, redisClient) {
this.queueName = queueName;
this.redisClient = redisClient;
this.queueKey = "queues:" + queueName;
this.timeout = 0;
}
Queue.prototype.size = function (callback) {
this.redisClient.llen(this.queueKey, callback);
};
Queue.prototype.push = function(data) {
this.redisClient.lpush(this.queueKey, data);
};
Queue.prototype.pop = function(callback) {
this.redisClient.brpop(this.queueKey, this.timeout, callback);
};
module.exports = { Queue: Queue };
Upvotes: 1
Reputation: 14906
It's because you're exporting Queue
when executing it. So it obviously hasn't yet been exported when you call require('./queue')
. So in order to fix this, you need to export Queue
on runtime instead.
function Queue(queueName, redisClient) {
this.queueName = queueName;
this.redisClient = redisClient;
this.queueKey = "queues:" + queueName;
this.timeout = 0;
}
Queue.prototype.size = function (callback) {
this.redisClient.llen(this.queueKey, callback);
};
Queue.prototype.push = function(data) {
this.redisClient.lpush(this.queueKey, data);
};
Queue.prototype.pop = function(callback) {
this.redisClient.brpop(this.queueKey, this.timeout, callback);
};
module.exports = Queue;
// Usage
var Queue = require("./queue");
var logsQueue = new Queue("logs", client);
Upvotes: 2