Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js (npm) accessing files inside installed module

Tags:

node.js

npm

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"?

like image 559
Yanick Rochon Avatar asked Mar 06 '14 07:03

Yanick Rochon


People also ask

How do I view npm files?

on windows: c/Program\ Files/nodejs/node_modules/npm/npmrc.

Which module is used to read files in node JS?

Reading and Writing the file in Node. js is done by using one of the coolest Node. js modules called fs module, it is one of the most well-known built-in Node. js modules out there.

Does node js have access to the file system?

Node.js as a File ServerThe Node.js file system module allows you to work with the file system on your computer. To include the File System module, use the require() method: var fs = require('fs');


1 Answers

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.

like image 172
alex Avatar answered Sep 30 '22 18:09

alex