jsonnode.jsnpmpackage.jsonnpm-shrinkwrap

Transparently install npm packages offline, from a custom filesystem directory


Editor's note: The question's original title was "Use npm install to install node modules stored on a local directory", which made the desire to transparently redefine the installation source less obvious. Therefore, some existing answers suggest solutions based on modifying the installation process.

I know this is a simple thing, but I'm quite new to anything in this area so after searching around and constantly finding answers that weren't really what I want I figured I'd just ask directly.

I currently have a process that is run in directory FOO that calls npm install. Directory FOO contains a package.json and a npm-shrinkwrap.json file to specify the modules (bluebird, extend, and mysql in this case but it doesn't really matter) and versions. This all works perfectly fine.

But now instead of reaching out to the internet to get the modules I want to have them stored in local directory BAR and have the process in foo use npm to install them from there. I can not store them permanently in FOO but I can in BAR for reasons outside my control. I know this is relatively simple but I can't seem to get the right set of commands down. Thanks for the help.


Solution

  • Note: This answer originally suggested only redefining the cache location. While that works in principle, npm still tries to contact the network for each package, causing excessive delays.

    I assume your intent is to transparently change the installation source: in other words: you don't want to change your package, you simply want to call npm install as before, but have the packages be installed from your custom filesystem location, offline (without the need for an Internet connection).

    There are two pieces to the puzzle:

    Assuming you've set cache-min globally or through an environment variable, running npm install should now serve the packages straight from your custom cache location.

    Caveats:


    Sample bash script:

    #!/usr/bin/env bash
    
    # Set environment variables that set npm configuration items to:
    #  - redefine the location of the cache folder
    #  - make npm look in the cache only (assuming the packages are there)
    # Note that by doing this inside a script the changes will only take effect
    # in the script and NOT persist.
    export npm_config_cache='/path/to/BAR' npm_config_cache_min=9999999999
    
    # Now cd to your package and invoke `npm install` as usual.
    cd '/path/to/project'
    npm install