Can I put the npm node_modules directory outside of my ‘webroot’
I’m new to Node but am enjoying myself so far. I was trying to move my
node_modules (libraries) directory outside of the public ‘webroot’ and need advice and guidance.
I’ve setup my simple expressJS based Node project as follows:
/my_project /config /public /node_modules server.js
I was wondering if there was any way I could have the
/node_modules dir outside of my webroot and not break my application. I’m just so used to keeping the bare minimum in my publicly exposed webroot and don’t feel right with the libs being in there. Call me old fashioned but that’s how I’m used to doing stuff in the PHP and C# world.
If I setup the project as follows:
/my_project /config /node_modules /public server.js
then it all goes wobbly and Node’s
require() magic breaks.
I’ve tried the following:
var express=require('../express'); which doesn’t work either giving me the ‘Cannot Find module’ type error.
- Is what I’m asking even possible, if so then how?
- Are there any major risks with me having my libs in a webroot or have I missed something fundamental here with the way Node works.
What do you guys do, what is best practice for production apps?May I have some examples of your production practices and why.
Problem courtesy of: Jujhar Singh
1. Is it possible to have modules in a folder outside of the project
2. Are there any major risks with having modules in a webroot?
Assuming that you by “webroot” mean in the root of the server or any folder outside of your project: yes. It is possible to install modules globally with npm using the g-flag:
npm install -g express . This generally considered bad practice as different projects may depend on different versions of the same module. Installing locally allows different projects to have different versions.
If you’re using version control and don’t want to check in the external modules, a common (and standard in npm) pattern is to ignore
./node_modules and specify dependencies in a package.json file.
3. “What is best practice for production apps?”
Not a good fit for SO, but since I’m at it I’ll give it a shot anyway. If you use grunt (a very popular task automation tool) you’ll usually end up with a structure like this:
/my_project /node_modules /lib # actual project files /public # files that are meant to be sent to clients /test package.json # specifies dependencies, main script, version etc README.md # optional
This structure has the advantages of clearly separating core files, dependencies and any tests while keeping it all in the same folder.
Solution courtesy of: Andreas Hultgren
原文 : Node.js Recipes