Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I require a module using node from the command line?

Tags:

node.js

I'm using Mac OSX. I've installed node via Homebrew. I've installed my library (MomentJS) via npm install -g moment.

When I type node in the command line, I get the NodeJS console, it looks like:

>

Now, let's say I want to use the moment library. If I type:

var moment = require('moment'); 

I get the following error:

Error: Cannot find module 'moment'

How might I configure and require an external library using Node from the command line?

like image 739
YPCrumble Avatar asked Jan 11 '16 01:01

YPCrumble


People also ask

How do I run a node module from the command line?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.

How do I use require in NodeJS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

Which command is used to import the required modules in NodeJS?

Importing from core modules: These modules are inbuilt in Node. js and can be imported as: const var = require('fs');


1 Answers

You can execute the following:

npm install moment # module must be installed locally node --require moment 

And enter the following:

var moment = require('moment'); moment().format(); 

From the man page:

-r, --require          module to preload at startup 

According to the source, it appears that node --require will not search for global modules in version 4.2.x and will not raise any errors if the module is installed globally and not locally.

like image 97
ordonezalex Avatar answered Sep 19 '22 22:09

ordonezalex