我正在使用Node.js学习Redis以实现Queue系统
带有文件“ 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();
和“ 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;
}
当我尝试运行它时会生成错误:
node producer_worker.js
var logsQueue = new queue.Queue("logs", client)
TypeError: queue.Queue is not a constructor
我已多次检查以确保我的代码与书中的代码一致。
如何修复TypeError?
答案 0 :(得分:1)
您必须从函数范围中提取一些代码:
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 };
答案 1 :(得分:1)
这是因为执行时正在导出<div class="row" >
{% block content %}
<p>INFT : {% 'inft' %}</p>
{% endblock %}
</div>
。因此,当您调用Queue
时,显然还没有将其导出。因此,为了解决此问题,您需要在运行时导出require('./queue')
。
Queue