Installing npm dependencies from package.json into a custom node_modules location

I’m working on a project called myproject and I have a package.json file in my main folder. I need to install all the dependencies into a particular node_modules folder but I’m having trouble getting it to work right.

Expected outcome

I have some dependencies like libraryX and libraryY. I want my folder structure to look like this:

node_modules/
  libraryX
  libraryY
myproject/
  package.json
  src/
  ..

Current problem

When I try npm install myproject/ I end up with this mess:

node_modules/
  myproject/
    node_modules/
      libraryX
      libraryY
    package.json
    src/
    ..
myproject/
  package.json
  src/
  ..

Npm creates a duplicate of my entire project folder inside node_modules and puts all the packages in yet another nested node_modules folder.

I get why this happens when you’re installing a package for use in other projects. But my application runs standalone and I just want to install dependencies in a specific location. What’s the best way to handle this?

Had the same headache. run npm install --production --no-optional inside your myproject directory, then just copy the entire node_modules folder to where you need it. Not pretty, but it works every time without npm screwing up the package paths.

I hit the same issue when deploying to a server with limited disk space. This happens because npm treats your project as a package when you specify a path like that. Instead of npm install myproject/, cd to the parent folder and run npm install --prefix ./node_modules ./myproject. This installs dependencies from your project’s package.json directly into the target node_modules folder without the nested structure. Another option that worked for me: install normally in your project, then symlink from your desired location to the actual node_modules. Just heads up - some deployment tools don’t play nice with custom node_modules locations, so test it thoroughly before deploying.

You’re overcomplicating this. The problem is you’re treating your own project like a package instead of just installing its dependencies. Go to your myproject directory and run npm install --prefix ../node_modules or use --modules-folder to set a custom location. But honestly, I’ve found it’s more reliable to just modify your project config to point to the custom node_modules spot. Set the NODE_PATH environment variable or create a .npmrc file with prefix=../node_modules. Then Node.js will check your custom location without creating that messy nested structure. Bottom line: run npm install from inside your project directory, not from outside targeting it.