我正在学习用Node.js实现队列系统的redis。
使用文件"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我已经检查了多次,以确保我的代码与book的代码一致。
我怎样才能修复TypeError?
发布于 2018-08-14 18:43:28
这是因为您在执行Queue时将其导出。所以当你调用require('./queue')的时候,它显然还没有被导出。因此,为了解决这个问题,您需要在运行时导出Queue。
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);发布于 2018-08-14 18:42:31
你必须从函数作用域中提取一些代码:
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 };
https://stackoverflow.com/questions/51839385
复制相似问题