Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help requiring a npm module in node.js

I feel like I'm missing some very basic here...

So I install a npm library with npm install somelib. And from what I have read I should then be able to simply do a

var somelib = require('somelib');

But it fails to find anything. I do have a node_modules directory at the root of my app, but it doesn't seem to pick it up.

I tried require.paths.push('node_modules') but it doesn't help. The only thing that seems to work is this:

require.paths.unshift('.');
var somelib = require('node_modules/somelib/lib/somelib');

Which makes me feel like this is far more work than I actually need to do to load a npm library. What am I doing wrong here? I thought that installing modules in the app meant I didnt have to futz with environment variables or paths much?

like image 875
Alex Wayne Avatar asked Jun 24 '11 05:06

Alex Wayne


2 Answers

It's possible that somelib does not have a main file defined in their package.json or that it is incorrectly referenced. If somelib doesn't have a main but does have a directories.lib then you can do require('somelib/thefile.js') instead.

If somelib is written in coffeescript and your app isn't, you'll need to require('coffee-script') first.

Update: as js2coffee is coffeescript, I'm going with you need to do the latter.

like image 80
balupton Avatar answered Sep 18 '22 13:09

balupton


Having the specific module name instead of "somelib" might help... but check the package's package.json file. Display the require.paths and compare. Read up on node's module system

like image 42
Amadan Avatar answered Sep 19 '22 13:09

Amadan