需要一个带有函数的对象字面量

requiring an object literal with functions

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

有一些代码可以设置 Apple 的推送网络,然后通过 server.apnConnection

上的变量附加自身

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

index.js

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

applepush.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;
        }
    }
};

错误:

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)

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 使其 returns 成为对象而不是函数。不过好像这个函数的目标是设置一个服务器,你可能不希望这个服务器一加载模块就设置好。