Node.js TypeError: object is not a function

I'm trying to run Mike Wilson's book sample app, but receiving the following error:

pcassiano@...:~/socialnet$ sudo node app.js

/home/pcassiano/socialnet/app.js:60
  require('./routes/' + routeName)(app, models);
                                  ^
TypeError: object is not a function
    at /home/pcassiano/socialnet/app.js:60:35
    at Array.forEach (native)
    at Object.<anonymous> (/home/pcassiano/socialnet/app.js:57:26)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

i'm running the latest code from the book's repo.

what should i do in order to run this sample app properly?

thanks in advance.

You likely have .js files in the routes directory that do not export a function.

app.js is calling require on all files in the routes directory and then calling them as a function. So if any of those files do not follow the general pattern below you'll get the error you're seeing:

module.exports = function(app, models) {
  // Add this file's routes using app.get, etc. calls.
  ...
};

The error reports that the value of require('./routes/' + routeName) is not a function. So you have only one real possible source of the problem.

If './routes/'+routeName doesn't exist, node should throw an error (in v0.8.16 at least), so that isn't it. So the most obvious one is that the module being loaded doesn't export a function (as the error suggests).

You should run console.log('routeName: ', routeName) right before the require statement that is on line 60 of app.js and try running it again. Then, after finding the value of routeName, look in the file it's trying to open. Odds are either module.exports is either exporting an object (or an array, string etc), or is not set at all.

If you're adding routes in the routes folder, take care to follow the same exporting style as the author, namely module.exports = function(app, models) {...}