Yanick Rochon
Yanick Rochon

Reputation: 53531

Node.js (npm) accessing files inside installed module

I am implementing a Node module and I'd like the users to optionally be able to require some files part of the module. For example :

var M = require('my-module');
var Foo = require('my-module/foo');

Considering that my module structure is like this :

./my-module
  +- lib
  |  +- foo
  |  |  +- index.js
  |  +- index.js
  +- package.json

And this is the basic package.json file :

{
  "name": "my-module",
  "version": "0.0.1",
  "description": "My very own super fun module.",
  "main": "lib/index.js"
}

Note: unecessary keys were omitted for clarity, ex: dependencies, keywords, author, etc.

How would the package.json can be modified to allow this "feature"?

Upvotes: 8

Views: 3951

Answers (1)

alex
alex

Reputation: 12265

Change your module structure to this:

./my-module
  +- lib
  |  +- foo
  |  |  +- index.js
  |  +- index.js
  +- index.js
  +- foo.js
  +- package.json

Or even better, change require('my-module/foo') to require('my-module').Foo like most of the modules do.

Setting main in package.json is a wrong thing to do (because package.json is npm's own metadata and shouldn't have anything to do with node.js, think about installing the package from bower for example), so you shouldn't be using that anyway.

Upvotes: 4

Related Questions