Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS require a global module/package

People also ask

How do I use global package in NodeJS?

local packages are installed in the directory where you run npm install <package-name> , and they are put in the node_modules folder under this directory. global packages are all put in a single place in your system (exactly where depends on your setup), regardless of where you run npm install -g <package-name>

For what require () is used in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What is global module in NodeJS?

Global modules are node packages that are installed on your system rather than your project directory. They allow us to use the package as a tool anywhere on the local computer. By saying global, we are talking about the scope of usage of these modules.

Do you need to use require () to get the global object?

The require module, which appears to be available on the global scope — no need to require('require') . The module module, which also appears to be available on the global scope — no need to require('module') .


In Node.js, require doesn't look in the folder where global modules are installed.

You can fix this by setting the NODE_PATH environment variable. In Linux this will be:

export NODE_PATH=/usr/lib/node_modules

Note: This depend on where your global modules are actually installed.

See: Loading from the global folders.


After you install package globally you have to link the local project with global package

npm install express -g
cd ~/mynodeproject/
npm link express  

See here


Apologies for the necromancy but I'm able to specify hard-coded paths to globally installed modules:

var pg = require("/usr/local/lib/node_modules/pg");

This isn't perfect but considering that Unity3d tries to "compile" all javascript that is included in the project directory I really can't install any packages.


As per documentation, Node.js will search in the following locations by default:

  1. Path specified in the NODE_PATH environment variable.

    Note: NODE_PATH environment variable is set to a colon-delimited list of absolute paths.

  2. Current node_modules folder. (local)

  3. $HOME/.node_modules (global)

    Note: $HOME is the user's home directory.

  4. $HOME/.node_libraries (global)
  5. $PREFIX/lib/node (global)

    Note: $PREFIX is Node.js's configured node_prefix.

    To check the current value of node_prefix, run:

    node -p process.config.variables.node_prefix
    

    Note: Prefix corresponds to --prefix param during build and it's relative to process.execPath. Not to confuse with value from the npm config get prefix command.source

If the given module can't be found, that means it is not present in one of the above locations.

Location of global root folder where modules are installed can be printed by: npm root -g (by default the path is computed at run-time unless overridden in npmrc file).

Solution

You can try the following workarounds:

  • Specify your global module location in NODE_PATH environment variable. E.g.

    echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
    

    To test and print the value of NODE_PATH, run:

    echo 'console.log(process.env.NODE_PATH); require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node 
    
  • For more permanent solution, link your $HOME/.node_modules global user folder to point to the root folder, by running this command:

    ln -vs "$(npm root -g)" "$HOME"/.node_modules
    

    Then re-test it via: echo 'require("forever")' | node command.

  • Temporary change the current folder to where the extension has been installed globally, before invoking the script. E.g.

    npm install -g forever
    cd "$(npm root -g)"
    echo 'require("forever")' | node
    cd -
    
  • Configure global installation destination in npm userconfig file (see: npm help 5 npmrc) or by userconfig param (--prefix).

    To display the current config, run: npm config list.

    To edit the current config, run: npm config edit.

  • Specify the full path of node modules location when calling require(). E.g.

    require("/path/to/sub/module")
    
  • Install the package to custom location, e.g.

    npm install forever -g --prefix "$HOME"/.node_modules
    

    However, the installation will go under ~/.node_modules/lib/node_modules/, so the location still needs to be added.

    See: npm local install package to custom location

  • Create a symlink in the current folder from the location of the global package. E.g.

    npm link forever
    

I know this is an old question, but I ran into this when trying to do some version checking using semver in a preinstall script in package.json. Since I knew I can't depend on any local modules installed, I used this to require semver from the global node_modules folder (as npm depends on it I know it's there):

function requireGlobal(packageName) {
  var childProcess = require('child_process');
  var path = require('path');
  var fs = require('fs');

  var globalNodeModules = childProcess.execSync('npm root -g').toString().trim();
  var packageDir = path.join(globalNodeModules, packageName);
  if (!fs.existsSync(packageDir))
    packageDir = path.join(globalNodeModules, 'npm/node_modules', packageName); //find package required by old npm

  if (!fs.existsSync(packageDir))
    throw new Error('Cannot find global module \'' + packageName + '\'');

  var packageMeta = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json')).toString());
  var main = path.join(packageDir, packageMeta.main);

  return require(main);
}

I like this approach because this doesn't require the install of any special modules in order to use.

I didn't go with a NODE_PATH solution like others have suggested since I wanted to get this to work on anyone's machine, without having to require additional configuration/setup before running npm install for my project.

The way this is coded, it is only guaranteed to find top-level modules (installed using npm install -g ...) or modules required by npm (listed as dependencies here: https://github.com/npm/npm/blob/master/package.json). If you are using a newer version of NPM, it may find dependencies of other globally installed packages since there is a flatter structure for node_modules folders now.

Hope this is useful to someone.


You can use the package requireg to solve this problem:

var forever = require('requireg')('forever')

will do the trick.

Also, there's another module, global-npm, while specific to just using the global npm, you can look at the short code and see how the technique works.


For CLI utilities that depend on big modules, like puppeteer, I like to spawn a npm root -g and use it to require the global module.

try {
  const root = require('child_process').execSync('npm root -g').toString().trim()
  var puppeteer = require(root + '/puppeteer')
} catch (err) {
  console.error(`Install puppeteer globally first with: npm install -g puppeteer`)
  process.exit(1)
}