Table of Contents

About

NODE_PATH is:

  • Node reacts to others environment variable. See Node - Environment variable (NODE_PATH , )
  • Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
    • 1: HOME/.node_modules
    • 2: HOME/.node_libraries
    • 3: PREFIX/lib/node (PREFIX is Node.js's configured node_prefix.)

Snippet

How to change it programmatically ?

let path = require("path");
// New search path
let absolutePathToModule1 = path.resolve("./path/to/module1"); 
let absolutePathToModule2 = path.resolve("./path/to/module2"); 
let nodeSearchPaths = absolutePathToModule1+path.delimiter+absolutePathToModule2;
// Overwrite and implements
if(typeof process.env.NODE_PATH !== 'undefined'){
        process.env.NODE_PATH = process.env.NODE_PATH + path.delimiter + nodeSearchPaths ;
} else {
   process.env.NODE_PATH = nodePaths;
}
require("module").Module._initPaths();

Be aware that your test environment may implement its own module loader and may not respond to this hack. This is the case of Jest for instance where you should set the modulepaths

How to change it at start in package.json ?

In package.json, you need to set it up in:

  • the script node
  • with the cross-env cli to support linux and windows

Example:

"scripts": {
       "dev": "cross-env NODE_PATH=./my/module/home/directory main.js",
}

How to split it / filter / map

process.env.NODE_PATH = (process.env.NODE_PATH || '')
  .split(path.delimiter)
  .filter(folder => folder && !path.isAbsolute(folder))
  .map(folder => path.resolve(appDirectory, folder))
  .join(path.delimiter);

Syntax

The syntax is the same than PATH environment variable (search path for executable)

  • Linux
NODE_PATH=path[:…]
  • Windows
NODE_PATH=path[;…]

Documentation / Reference