首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError: queue.Queue不是构造函数

TypeError: queue.Queue不是构造函数
EN

Stack Overflow用户
提问于 2018-08-14 18:33:23
回答 2查看 1.1K关注 0票数 0

我正在学习用Node.js实现队列系统的redis。

使用文件"producer_worker.js“

代码语言:javascript
复制
// 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“

代码语言:javascript
复制
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;  
}

当我尝试运行它时,它会产生错误:

代码语言:javascript
复制
node producer_worker.js 
var logsQueue = new queue.Queue("logs", client)
TypeError: queue.Queue is not a constructor

我已经检查了多次,以确保我的代码与book的代码一致。

我怎样才能修复TypeError?

EN

回答 2

Stack Overflow用户

发布于 2018-08-14 18:43:28

这是因为您在执行Queue时将其导出。所以当你调用require('./queue')的时候,它显然还没有被导出。因此,为了解决这个问题,您需要在运行时导出Queue

代码语言:javascript
复制
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);
票数 2
EN

Stack Overflow用户

发布于 2018-08-14 18:42:31

你必须从函数作用域中提取一些代码:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51839385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档