Node - NODE_PATH

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





Discover More
CommonJs (NodeJs) - Require

The import functionality implementation of commonjs (and then node) is done via the require function require basically: reads a Javascript file (generally a CommonJs module but it may be any javascript...
Javascript - Module Loader (Script Loader)

A loader searches and loads module and script into the javascript engine (environment). From the main script, they will: create a dependency graph from the require and import statement find them...
Javascript Module - Import (Es Module)

This page is the import statement defined in the es module specification The ES6 import is: a function for dynamic import (performed at runtime time) or a statement for static import (performed...
Node - Environment variable (NODE_PATH , )

in the Node process (Built-In|Well known) node environment variable Cli...



Share this page:
Follow us:
Task Runner