Erik Erik - 1 year ago 78
Javascript Question

requiring an object literal with functions

I'm trying to clean up some code I found in a hapi server


There's some code that sets up Apple's Push Network , then attaches itself via a variable on the

my problem is when i try to call functions that I had setup .. they are missing / not there.


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


'use strict';

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

module.exports = function() {

var options = {
gateway: '',
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);
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.badge = 1;
return note;

Error :

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)

Answer Source

applepush.js exports a function, not an object. The note member you are looking for is a member of the object that returns the exported function.

You probably should write:

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

Another solution is to modify applepush.js so that it returns an object instead of a function. However it seems that the goal of this function is to set up a server, and you may not want this server to be set up as soon as the module is loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download