Search code examples
node.jsnpmdirectory-structurenode-modules

Node.js: Where To Place Internal Modules In Folder Structure?


The Situation

I often see Node.js applications with the following structure:

Common pattern:

  • lib/ or src/ - the self-written code
    • index.js - main code
    • internal modules... (e.g. self-written for this project)
  • node_modules
    • external modules... (e.g. taken from another project)
  • package.json

My Problem

What I don't like about this pattern:

  • I don't feel comfortable about it because you have to explicitly specify the directory path of the internal modules when require()ing:

    // /lib/index.js
    
    var internalMod = require('./internal'); // `require('internal')` (without path) wouldn't work
    internalMod.doSomething();
    

My Idea

So I think it would be a good idea also to place internal modules in an node_modules folder (somewhere in the project). So node would be able to find them, even if you don't explicitly specify the path.

For example:

  • src/ - the self-written code
    • index.js - main code
    • node-modules - for internals
      • internal modules...
  • node_modules - for externals
    • external modules... (e.g. taken from another project)
  • package.json

My Question

  1. Are there any cons about my plan?
  2. Is there another idea where to place internal modules in folder structure?

Thanks for your answer (or comment). - If anything is unclear, please comment.


Solution

  • Perhaps you could use npm link to pull your modules into node_modules? See: https://docs.npmjs.com/cli/link