node module.export和recursion

时间:2014-10-23 20:25:38

标签: node.js

我正在开发一个节点应用程序,它本质上是一个简单的AWS SQS轮询器,可以坐下来收听不同队列中的新项目。

这是我的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

的错误

2 个答案:

答案 0 :(得分:10)

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;

请注意,我只回答了你特别提出的问题。我没有考虑与代码相关的任何架构问题。

答案 1 :(得分:1)

function functionName(has = false){
  var total = 0;
  if(has){
    functionName(true)
  } else {
    // Todo
  }
}

module.exports.functionName = functionName;