How to use npm packages with REPL sessions — Node.js

Introduction

One tool that I find incredibly useful when working with Node.js is the ability to quickly start a REPL session and double-check whenever in doubt. For example, let’s say I’m unsure if the array’s push method returns a reference to itself (so I can do method chaining), I can get the answer in seconds.

REPL session — Check behaviour of the push method

Although I get most of my questions answered this way, sometimes I need the same quick approach for an external module. Luckily, there is a simple way to do so, and in the rest of this post, we will explore how can we load those external modules into REPL sessions.

Loading external npm module

When requiring a module inside of a Node.js process (REPL session) it inspects multiple locations to load the requested module. The full list of paths checked are shown image bellow (see paths: [])

Array of locations inspected by Node.js process for modules

Put in other words, if a target module is located in one of the listed folders we are able to access (require) it in a REPL session.

An easy way to add a new location to the paths array is via a special environment variable — NODE_PATH.

If we start our Node.js process by prefixing it with the mentioned env variable, for example:

NODE_PATH=/THIS-IS-A/SPECIAL-PATH/I-JUST-ADDED node

NODE_PATH variable shows up in the list of paths

Once again, if we want to be able to require an external module, all we have to do is to provide a path to it via the NODE_PATH env variable.

In the following example, we will load a globally installed package — momentjs. We can achieve this simply by providing the path to the global node_modules directory. Conveniently, npm CLI provides command which returns a full path to the global node_modules directory.

npm root -g

Get path to the global node_modules

If we put the output of the command above into the NODE_PATH env, we will be able to access globally installed packages.

NODE_PATH=$(npm root -g) node

Now we have a convenient way to experiment with the momentjs module (which i have installed globally).

Experiment with momentjs in a REPL session

Additionally, we can add it as an alias to our bash profile:

alias repl="NODE_PATH=$(npm root -g) node"

Remember to source it or restart your terminal window.

It’s not recommended to use this approach of loading libraries outside of a REPL playground. All project dependencies should be specified in the package.json file for easier collaboration, portability, and generally — better software.