view raw
e2l3n e2l3n - 6 months ago 41
Javascript Question

Load module using node.js require

I'm building a node.js app using express and jade frameworks. The app has the standard skeleton, that's how it looks the main directory :

  • app.js

  • bin

  • npm-debug.log

  • views

  • node_modules

  • package.json

  • public

The problem occurs when I try to load the module in a js file (called lets say x.js) within the public directory. That's where I've implemented some logic tightly connected to user-action event handling. So in other words when someone clicks on a button 'connect', I'd like to establish connection using The problem is that when I add this line

var socket_io = require(''); in x.js (x.js is located in the /public dir)

the whole functionality suddenly stops working, I guess due to the fact that the module is not loaded although the var socket_io isn't used anywhere below within the x.js file. If I add the line var socket_io = require(''); to app.js everything works. I looked into this SO question but with no success.
Can someone explain why is this happening and what am I doing wrong?

Edit: Just to clarify that I've added '' to the package.json file. Also installed both globally and locally using npm install (-g) command.


To init you need some crucial things, like the server var that is init in app.js file. So, if you try to require out of app.js and you try to init, then you could have some troubles. Because can't be init without the server var in your case.

If you try to require and not init it. I think you will have not problem. So try to understand the section that is related to Express in the documentation :

Then you can try to use the npm module for express and :

Or you can deal with socket.of() method :

In any event, you should init with the server var. So, you can make your module to manage behavior, define some methods, etc. For this purpose, you can passe in argument to your route files. See here :Use inside a express routes file Then, that logic allow you to use anywhere in your app.