Node module.export and recursion

I'm working on a node app, which is essentially a simple AWS SQS poller that has to sit and listen for new items in different queues.

Here is mine 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);
        }
    }
}

      

The problem I am facing is trying to call again readMessage();

. I get an errorReferenceError: readMessage is not defined

+3


source to share


1 answer


module.exports

is a simple object exposed to external modules that have a method readMessage

. readMessage()

should be module.exports.readMessage()

.

Also I would suggest creating a variable and then exporting it:



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;

      

Please note that I only answered the question you asked. I have not taken into account any architectural issue related to the code.

+7


source







All Articles