要求具有函数的对象文字

时间:2016-05-22 00:16:21

标签: javascript hapijs

我正在尝试清理我在hapi服务器server.apnConnection中找到的一些代码。

有一些代码可以设置Apple的推送网络,然后通过server = require('./config/server/hapi.js')(config, process.env.NODE_URL); server.apnConnection = require('./config/server/applepush.js'); server.apnConnection.note("test"); 上的变量附加自己

我的问题是当我尝试调用我已设置的函数时......它们缺失/不存在。

index.js

'use strict';

var apn = require('apn');
var Path = require('path');

module.exports = function() {

    var options = {
        gateway: 'www.mapple.com',
        errorCallback: function(errorNum, notification){
            console.log('Error is: %s', errorNum);
            console.log('Note ' + JSON.stringify(notification));
        },
        cert: process.env.APPLE_CERT || Path.join(config.rootPath, '../cert.pem'),
        key:  process.env.APPLE_KEY || Path.join(config.rootPath, '../key.pem'),
        enhanced: true,
        production: false,
        cacheLength: 100,
        port: 2195
    };
    var apnConn = new apn.Connection(options);
    apnConn.on('connected',function(){
        console.log('connected to apn');
    });
    apnConn.on('transmitted', function(notification, device) {
        console.log('Notification transmitted to:' + device.token.toString('hex'));
    });
    apnConn.on('transmissionError', function(errCode, notification, device) {
        console.error('Notification caused error: ' + errCode + ' for device ', device, notification);
        if (errCode === 8) {
            console.log('A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox');
        }
    });
    apnConn.on('timeout', function () {
        console.log('APNS Connection Timeout');
    });

    apnConn.on('disconnected', function() {
        console.log('Disconnected from APNS');
    });
    apnConn.on('socketError', console.error);

    return {
        init: apnConn,
        note: function (obj) {
            var note = new apn.Notification();
            note.setAlertText(obj.alert);
            note.badge = 1;
            return note;
        }
    }
};

applepush.js

server.apnConnection.note("test");
                 ^
TypeError: undefined is not a function
    at Object.<anonymous> (~/server/index.js:60:22)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.runMain [as _onTimeout] (module.js:501:10)
    at Timer.listOnTimeout (timers.js:110:15)

错误:

{{1}}

1 个答案:

答案 0 :(得分:1)

applepush.js导出一个函数,而不是一个对象。您要查找的对象由导出的函数返回。

您可能应该写下这样的内容:

server = require('./config/server/hapi.js')(config, process.env.NODE_URL);
// Note the function call.
server.apnConnection = require('./config/server/applepush.js')();
server.apnConnection.note("test");

另一个解决方案是修改applepush.js,使其返回一个对象而不是一个函数。但是,似乎此功能的目标是设置服务器,并且您可能不希望在加载模块后立即设置此服务器。

相关问题