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?
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.
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).
Importing from core modules: These modules are inbuilt in Node. js and can be imported as: const var = require('fs');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With