Javascript – Node.js app private modules. Where to put them

directory-structurejavascriptmodulesnode.js

The situation would be:

I develop 2 projects in my Node.js development environment, P1 and P2.

P1 required the development of two simple modules, mod1 and mod2, which are stored in P1/lib. Each one of this modules resolves find their external dependencies in P1/node_modules. Necessary dependencies for P1 have been installed in this folder via npm.

Now image we want to reuse mod1 in the other proyect P2, here's were my doubts come up. I could…

  • Just copy mod1 to P2/lib. Replication, so I don't even consider this option.

  • From P2, reference mod1 from P1: require($PROJECTS_DIR + '/P1/lib/mod1'). Not a good option, this way P2 would depend on P1.

  • Put mod1 into a higher level directory or using NODE_PATH, so that P1 and P2 can resolve it by just doint require('mod1'). However, when deploying, I should also deploy this higher level directory which seems a bit dirty.

  • I would like to treat mod1 as a npm module, so it can be easily installed in any project or environment, However, in this particular case, I can't publish the module to npm cause is too project-specific. I could create a private npm repository and put mod1 inside. The gist of this would be to set it up in order to be accessed also from the production envirnoment. Is it worth it?

  • What about putting it all together in node_modules? (external depencencies and my own libraries). That would be great since modules can be just required like `require('module'). But it also seems quite dirty.

  • Not sure how npm link would work when deploying. It creates a symbolic link, which is not followed when commiting code via Git or SVN. If I run npm install in production, will it also install the linked module?

None of the above quite satisfies me.
I don't know if one of these is suitable, or you guys have other suggestions, but, are there any preferred ways to structure own private libraries so that they can be easily reused in other projects?

Best Answer

Use npm link. It allows you to have a module wherever you want, and you can then "link" it in your project (a symbolic link will be created in your node_modules/ folder), thus you can use it with require('mod1'). Your module has to be npm-compatible.

More information here: https://docs.npmjs.com/cli/link

About your private concerns, npm thought about this and provides the private option. See here: https://docs.npmjs.com/misc/registry (Go to : "I don't want my package published in the official registry. It's private.")

For each module dependency, you can simply define them in the package.json.