我正在研究一个本质上是一个简单的AWS SQS轮询器的 Node 应用程序,该应用程序应该坐下来听不同队列中的新项目。

这是我的module.export:

module.exports = {
    readMessage: function(qParams, qType, tableName) {
        logger.debug(qType);

        SQS.receiveMessage(qParams, handleSqsResponse);

        function handleSqsResponse (err, data) {
            if(err) logger.error("handleSqsResponse error:" + err);
            if (data && data.Messages) {
                data.Messages.forEach(processMessage)
                readMessage(); // continue reading until draining the queue (or UPTIME reached)
            }
            else{
                logger.debug("no data in sqs.");
                // process.exit();
            }
        }

        // 'processing' is mainly writing to logs using winston. Could add here any transformations and transmission to remote systems
        function processMessage(sqsMessage){
            // Parse sqs messag
            var msgObj = JSON.parse(sqsMessage.Body);

            // Process
            logger.info(msgObj.Message);

            _.extend(qParams, { "ReceiptHandle": sqsMessage.ReceiptHandle });

            dbMap[qType](msgObj, qParams, tableName);
        }
    }
}

我遇到的问题是当我尝试再次调用readMessage();时。我收到ReferenceError: readMessage is not defined的错误

最佳答案

module.exports是一个普通对象,暴露给具有readMessage方法的外部模块。 readMessage()应该是module.exports.readMessage()

我也建议创建一个变量,然后将其导出:

var obj = {
    readMessage: function(qParams, qType, tableName) {
        logger.debug(qType);

        SQS.receiveMessage(qParams, handleSqsResponse);

        function handleSqsResponse (err, data) {
            if(err) logger.error("handleSqsResponse error:" + err);
            if (data && data.Messages) {
                data.Messages.forEach(processMessage)
                obj.readMessage(); // continue reading until draining the queue (or UPTIME reached)
            }
            else{
                logger.debug("no data in sqs.");
                // process.exit();
            }
        }

        // 'processing' is mainly writing to logs using winston. Could add here any transformations and transmission to remote systems
        function processMessage(sqsMessage){
            // Parse sqs messag
            var msgObj = JSON.parse(sqsMessage.Body);

            // Process
            logger.info(msgObj.Message);

            _.extend(qParams, { "ReceiptHandle": sqsMessage.ReceiptHandle });

            dbMap[qType](msgObj, qParams, tableName);
        }
    }
}

module.exports = obj;

请注意,我仅回答了您明确提出的问题。我没有考虑与代码相关的任何体系结构问题。

关于node.js - Node module.export和递归,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26536777/

10-11 05:57