Alex Wayne
Alex Wayne

Reputation: 187034

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?

Upvotes: 8

Views: 17570

Answers (2)

balupton
balupton

Reputation: 48650

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.

Upvotes: 4

Amadan
Amadan

Reputation: 198324

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

Upvotes: 1

Related Questions