nodejs can't find global modules [duplicate] - node.js

I am trying to setup Node on Mac OSX Lion. It all seems to work ok, but I can't seem to import anything modules from my global modules folder. I get the error,
Error: Cannot find module <module>
If I run this: node -e require.paths, the response I get is:
[ '/usr/local/lib/node_modules',
'/Users/Me/.node_modules',
'/Users/Me/.node_libraries',
'/usr/local/Cellar/node/0.4.12/lib/node' ]
Which is correct, my modules are indeed installed in /usr/local/lib/node_modules. When I try and run a script, however, I am getting this:
Error: Cannot find module 'socket.io'
at Function._resolveFilename (module.js:326:11)
at Function._load (module.js:271:25)
at require (module.js:355:19)
at Object.<anonymous> (/Users/Me/node/server.js:2:10)
at Module._compile (module.js:411:26)
at Object..js (module.js:417:10)
at Module.load (module.js:343:31)
at Function._load (module.js:302:12)
at Array.<anonymous> (module.js:430:10)
at EventEmitter._tickCallback (node.js:126:26)
My .bash_profile looks like this:
export PATH=/usr/local/mysql/bin:$PATH
export NODE_PATH=/usr/local/lib/node_modules
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:/usr/local/mysql/lib/"
Would really appreciate some help, I have no idea why I can't import any libraries.

Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)

If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)
However, this doesn't come without its problems.
npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.
As an alternative, you can install the packages locally as well as globally.
For additional information, see
https://nodejs.org/en/blog/npm/npm-1-0-link/
https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/

You can use npm link to create a symbolic link to your global package in your projects folder.
Example:
$ npm install -g express
$ cd [local path]/project
$ npm link express
All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')

Install any package globally as below:
$ npm install -g replace // replace is one of the node module.
As this replace module is installed globally so if you see your node modules folder you would not see replace module there and so you can not use this package using require('replace').
because with require you can use only local modules which are present in your node module folder.
Now to use global module you should link it with node module path using below command.
$ npm link replace
Now go back and see your node module folder you could now be able to see replace module there and can use it with require('replace') in your application as it is linked with your local node module.
Pls let me know if any further clarification is needed.

You can use require with the path to the global module directory as an argument.
require('/path/to/global/node_modules/the_module');
On my mac, I use this:
require('/usr/local/lib/node_modules/the_module');
How to find where your global modules are? --> Where does npm install packages?

Setting the environment variable NODE_PATH to point to your global node_modules folder.
In Windows 7 or higher the path is something like %AppData%\npm\node_modules while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/ but it depends on user configuration.
The command npm config get prefix could help finding out which is the correct path.
In UNIX systems you can accomplish it with the following command:
export NODE_PATH=`npm config get prefix`/lib/node_modules/

Easy answer is to run node in npm global root directory.
cd $( npm root -g ) && node

I am using Docker. I am trying to create a docker image that has all of my node dependencies installed, but can use my local app directory at container run time (without polluting it with a node_modules directory or link). This causes problems in this scenario. My workaround is to require from the exact path where the module, e.g. require('/usr/local/lib/node_modules/socket.io')

If you are on windows cmd, you can do it via FOR /f "tokens=* delims=" %A in ('npm root --quiet -g') do set "NODE_PATH=%A" or FOR /f "tokens=* delims=" %%A in ('npm root --quiet -g') do set "NODE_PATH=%%A" in a batch file.

require.paths is deprecated.
Go to your project folder and type
npm install socket.io
that should install it in the local ./node_modules folder where node will look for it.
I keep my things like this:
cd ~/Sites/
mkdir sweetnodeproject
cd sweetnodeproject
npm install socket.io
Create an app.js file
// app.js
var socket = require('socket.io')
now run my app
node app.js
Make sure you're using npm >= 1.0 and node >= 4.0.

Related

Error: Cannot find module 'webpack'

I'm just getting started with webpack and am having difficulty getting the multiple-entry-points sample to build. The webpack.config.js file in the example includes the line
var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin");
which fails for me with the error
Error: Cannot find module '../../lib/optimize/CommonsChunkPlugin'
Searching around, I found other examples of using the CommonsChunkPlugin with the expression
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin("common.js");
which fails with the error
ReferenceError: webpack is not defined
Some more searching found a number of examples including
var webpack = require('webpack');
and my build now fails with
Error: Cannot find module 'webpack'
I'm at a loss as to how to proceed.
Link globally installed package to your project:
npm link webpack
Checkout the official documentation of yarn link.
I solved the same problem by reinstalling, execute these commands
rm -rf node_modules
rm -f package-lock.json
npm install
rm is always a dangerous command, especially with -f, please notice that before executing it!!!!!
While working on windows, I've installed webpack locally and it fixed my problem
So, on your command prompt, go to the directory of which you want to run webpack, install webpack locally (without the -g) and enjoy...
Run below commands in Terminal:
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
Seems to be a common Windows problem. This fixed it for me:
Nodejs cannot find installed module on Windows?
"Add an environment variable called NODE_PATH and set it to %USERPROFILE%\Application Data\npm\node_modules (Windows XP), %AppData%\npm\node_modules (Windows 7), or wherever npm ends up installing the modules on your Windows flavor. To be done with it once and for all, add this as a System variable in the Advanced tab of the System Properties dialog (run control.exe sysdm.cpl,System,3)."
Note that you can't actually use another environment variable within the value of NODE_PATH. That is, don't just copy and paste that string above, but set it to an actual resolved path like C:\Users\MYNAME\AppData\Roaming\npm\node_modules
I was having this issue on OS X and it seemed to be caused by a version mismatch between my globally installed webpack and my locally installed webpack-dev-server. Updating both to the latest version got rid of the issue.
I was facing same problem, and I solved through this command, check this out will solve your issue.
rm -Rf node_modules
rm -f package-lock.json
npm install
Installing both webpack and CLI globally worked for me.
npm i -g webpack webpack-cli
If you have installed a node package and are still getting message that the package is undefined, you might have an issue with the PATH linking to the binary. Just to clarify a binary and executable essentially do the same thing, which is to execute a package or application. ei webpack... executes the node package webpack.
In both Windows and Linux there is a global binary folder. In Windows I believe it's something like C://Windows/System32 and in Linux it's usr/bin. When you open the terminal/command prompt, the profile of it links the PATH variable to the global bin folder so you are able to execute packages/applications from it.
My best guess is that installing webpack globally may not have successfully put the executable file in the global binary folder. Without the executable there, you will get an error message. It could be another issue, but it is safe to say the that if you are here reading this, running webpack globally is not working for you.
My resolution to this problem is to do away with running webpack globally and link the PATH to the node_module binary folder, which is /node_modules/.bin.
WINDOWS:
add node_modules/.bin to your PATH.
Here is a tutorial on how to change the PATH variable in windows.
LINUX:
Go to your project root and execute this...
export PATH=$PWD/node_modules/.bin:$PATH
In Linux you will have to execute this command every time you open your terminal. This link here shows you how to make a change to your PATH variable permanent.
On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.
As someone else suggested, the solution seems to be to install locally by not using the -g hint.
for me, it is a wrong error feedback.
there was config error in webpack.config.js,
delete the file and start over solved my issue
Open npm command prompt and -- cd solution folder
and then
just run npm link webpack in NPM cmd prommt and re build..
You can try this.
npm install --only=dev
It works for me.
In my case helped me changing the parent folder name and remove some & from this name, you can also try changing the name or folder where you keep your code.
Nothing suggested above worked for me (including the NODE_PATH variable). I created a sym link of "node_modules" from my local folder to the global AppData(eg below) and it worked like charm.
C:\Users\mmoinuddin\AppData\Roaming\npm>mklink /D node_modules c:\essportreact\day1\node_modules
symbolic link created for node_modules <<===>> c:\essportreact\day1\node_modules
C:\essportreact\day1>webpack
Hash: 2a82a67f90f9aa05ab4a
Version: webpack 1.15.0
Just found out that using Atom IDE terminal did not install dependencies locally (probably a bug or just me). Installing git bash externally and running npm commands again worked for me
I had a ton of issues getting a very simple .NET Core 2.0 application to build in VS 2017. This is the error from AppVeyor, however it was essentially the same thing locally
(some paths omitted for security) :
Performing first-run Webpack build...
module.js:327
throw err;
EXEC : error : Cannot find module '......../node_modules/webpack/bin/webpack.js'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:140:18)
at node.js:1043:3
csproj(25,5): error MSB3073: The command "node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js" exited with code 1.
Build FAILED.
I stumbled upon this question and answer, and I noticed my local instance also had the same warning sign over the {Project Root} -> Dependencies -> npm folder. Right clicking and hitting "Restore packages" got everything loaded up properly, and I was able to build successfully.
npm link webpack
worked for me.
My webpack configuration:
"webpack": "^4.41.2",
"webpack-dev-server": "^3.9.0",
"webpack-cli": "^3.3.10"
For Visual Studio users: Right click on the npm folder and "Restore Packages".
While the suggested solution (npm link webpack) worked locally, on my CI (GitHub actions) I had the same problem, and to resolve it I used:
npm i --save-dev webpack
Laravel Users
If none of the above options work for you, then you probably need to install Laravel-mix correctly. Here is how:
npm install laravel-mix --save-dev
Now create a webpack.mix.js file using this command:
touch webpack.mix.js
Add this code into your webpack.mix.js file:
mix.js('resources/js/app.js', 'public/js').postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]);
You probably will also need to create a tailwind.config.js file using the command touch tailwind.config.js and then add this code ainto it:
module.exports = {
content: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [require('#tailwindcss/forms')],
};
Finally run npm run dev
So there are quite few possible issues, in my case on windows:
I moved my project to a folder with an & in the name, which is fine for windows but it break npm. My solution was to remove the & from the name.
test&mocking -> test_and_mocking
What solved it for me was that the path to webpack.config was wrong in build.js
rm -rf node_modules
rm -rf package.json-lock
npm install --force or npm install --legacy-peer-deps

How to put local node package on path?

Newbie question. I have chosen not to install express with -g option. I did not use npm -g which would put it on the path globally. Instead it is installed in my local mac user directory. What I am not clear on is exactly what or how you put a package like express on the path so it can be invoked etc? What exactly needs to be on the path (node_modules?) so these packages are available just like a -g installation? I could have used home-brew I suppose but anyway, I now have all node packages and everything local. Another situation is that I am not able to run any of the nodejs tutorials. Although there might be smarter ways to do this, I wonder if sudo is really such a good way to install a development package ....
Now for example, I want to run the tutorial javascripting which is a nodejs tutorial. How do I do this. If I just type:
Mac1$ javascripting
it finds nothing.
Same for
Mac1$ express
UPDATE: THIS WAS ANSWERED IN THE COMMENTS
The commands exist in a hidden directory after a regular
install npm install express
in my case this the command goes here: /users/MAC1/node_modules/.bin
It is this path that needs to be placed on the $PATH as described in the first comment.
Thanks guys.
npm installes executable to two places. By default running a npm install in a project will install any binaries in ./node_modules/.bin. When you use the -g flag (npm install -g package-name) it will install into a global path. You can find out the global path by running npm bin -g. Add that to your path and globally installed executables will be accessible.
You can also add ./node_modules/.bin to your path to allow easy access to executables added by packages in your project folder. I admit to using this on a trusted local machine. However, this is very dangerous and not a recommended way to expose the executables in the node_modules directory.
Best alternative is to add the executable to the scripts section of the package.json file and then use npm run-script <command> which will auto prepend the ./node_modules/.bin when executing.
package.json
{
"scripts": {
"foo": "foo --arguments"
}
}
Example
$ npm install foo
$ ls ./node_modules/.bin
foo
$ npm run-script foo
# Executes:
./node_modules/.bin/foo --arguments

NodeJS require a global module/package

I'm trying to install globally and then use forever and forever-monitor like this:
npm install -g forever forever-monitor
I see the usual output and also the operations that copy the files to the global path, but then if I try to require("forever"); I get an error saying that the module wasn't found.
I'm using latest version of both node and npm and I already know about the change that npm made in global vs local install, but I really don't want to install localy on every project and I'm working on a platform that doesn't support link so npm link after a global install isn't possible for me.
My question is: why I can't require a globally installed package? Is that a feature or a bug? Or am I doing something wrong?
PS: Just to make it crystal clear: I don't want to install locally.
In Node.js, require doesn't look in the folder where global modules are installed.
You can fix this by setting the NODE_PATH environment variable. In Linux this will be:
export NODE_PATH=/usr/lib/node_modules
Note: This depend on where your global modules are actually installed.
See: Loading from the global folders.
After you install package globally you have to link the local project with global package
npm install express -g
cd ~/mynodeproject/
npm link express
See here
Apologies for the necromancy but I'm able to specify hard-coded paths to globally installed modules:
var pg = require("/usr/local/lib/node_modules/pg");
This isn't perfect but considering that Unity3d tries to "compile" all javascript that is included in the project directory I really can't install any packages.
As per documentation, Node.js will search in the following locations by default:
Path specified in the NODE_PATH environment variable.
Note: NODE_PATH environment variable is set to a colon-delimited list of absolute paths.
Current node_modules folder. (local)
$HOME/.node_modules (global)
Note: $HOME is the user's home directory.
$HOME/.node_libraries (global)
$PREFIX/lib/node (global)
Note: $PREFIX is Node.js's configured node_prefix.
To check the current value of node_prefix, run:
node -p process.config.variables.node_prefix
Note: Prefix corresponds to --prefix param during build and it's relative to process.execPath. Not to confuse with value from the npm config get prefix command.source
If the given module can't be found, that means it is not present in one of the above locations.
Location of global root folder where modules are installed can be printed by: npm root -g (by default the path is computed at run-time unless overridden in npmrc file).
Solution
You can try the following workarounds:
Specify your global module location in NODE_PATH environment variable. E.g.
echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
To test and print the value of NODE_PATH, run:
echo 'console.log(process.env.NODE_PATH); require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
For more permanent solution, link your $HOME/.node_modules global user folder to point to the root folder, by running this command:
ln -vs "$(npm root -g)" "$HOME"/.node_modules
Then re-test it via: echo 'require("forever")' | node command.
Temporary change the current folder to where the extension has been installed globally, before invoking the script. E.g.
npm install -g forever
cd "$(npm root -g)"
echo 'require("forever")' | node
cd -
Configure global installation destination in npm userconfig file (see: npm help 5 npmrc) or by userconfig param (--prefix).
To display the current config, run: npm config list.
To edit the current config, run: npm config edit.
Specify the full path of node modules location when calling require(). E.g.
require("/path/to/sub/module")
Install the package to custom location, e.g.
npm install forever -g --prefix "$HOME"/.node_modules
However, the installation will go under ~/.node_modules/lib/node_modules/, so the location still needs to be added.
See: npm local install package to custom location
Create a symlink in the current folder from the location of the global package. E.g.
npm link forever
I know this is an old question, but I ran into this when trying to do some version checking using semver in a preinstall script in package.json. Since I knew I can't depend on any local modules installed, I used this to require semver from the global node_modules folder (as npm depends on it I know it's there):
function requireGlobal(packageName) {
var childProcess = require('child_process');
var path = require('path');
var fs = require('fs');
var globalNodeModules = childProcess.execSync('npm root -g').toString().trim();
var packageDir = path.join(globalNodeModules, packageName);
if (!fs.existsSync(packageDir))
packageDir = path.join(globalNodeModules, 'npm/node_modules', packageName); //find package required by old npm
if (!fs.existsSync(packageDir))
throw new Error('Cannot find global module \'' + packageName + '\'');
var packageMeta = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json')).toString());
var main = path.join(packageDir, packageMeta.main);
return require(main);
}
I like this approach because this doesn't require the install of any special modules in order to use.
I didn't go with a NODE_PATH solution like others have suggested since I wanted to get this to work on anyone's machine, without having to require additional configuration/setup before running npm install for my project.
The way this is coded, it is only guaranteed to find top-level modules (installed using npm install -g ...) or modules required by npm (listed as dependencies here: https://github.com/npm/npm/blob/master/package.json). If you are using a newer version of NPM, it may find dependencies of other globally installed packages since there is a flatter structure for node_modules folders now.
Hope this is useful to someone.
You can use the package requireg to solve this problem:
var forever = require('requireg')('forever')
will do the trick.
Also, there's another module, global-npm, while specific to just using the global npm, you can look at the short code and see how the technique works.
For CLI utilities that depend on big modules, like puppeteer, I like to spawn a npm root -g and use it to require the global module.
try {
const root = require('child_process').execSync('npm root -g').toString().trim()
var puppeteer = require(root + '/puppeteer')
} catch (err) {
console.error(`Install puppeteer globally first with: npm install -g puppeteer`)
process.exit(1)
}
You can put this line in your .profile file:
export NODE_PATH="$(npm config get prefix)/lib/node_modules"
This will make node use the global path.
i tried following the other answers but what worked for me was
node_path = "C:\\Users\\{usename}\\AppData\\Roaming\\npm\\node_modules"
const *modulename* = require(node_path + "\\" +'*modulename*');
npm install express -g
cd ~/mynodeproject/
npm link express
This will link your local project folder to global node_modules.

NPM global install "cannot find module"

I wrote a module which I published to npm a moment ago (https://npmjs.org/package/wisp)
So it installs fine from the command line:
$ npm i -g wisp
However, when I run it from the command line, I keep getting an error that optimist isn't installed:
$ wisp
Error: Cannot find module 'optimist'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/usr/local/lib/node_modules/wisp/wisp:12:10)
at Object.<anonymous> (/usr/local/lib/node_modules/wisp/wisp:96:4)
at Module._compile (module.js:449:26)
at Object.exports.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:68:25)
at compileScript (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:135:29)
at fs.stat.notSources.(anonymous function) (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:110:18)
However, I have specified in package.json as a dependancy:
{
"name": "wisp",
"author": "Brendan Scarvell <bscarvell#gmail.com>",
"version": "0.1.0",
"description": "Global nodejs file server",
"dependencies": {
"optimist": "~0.3.4"
},
"repository": "git://github.com/tehlulz/wisp",
"bin": {
"wisp" : "./wisp"
}
}
Does anyone know what to do to get this running? I know its to do with the bin part adding the executable to bin and the node_modules in that directory being empty. No idea how to resolve this.
For anyone else running into this, I had this problem due to my npm installing into a location that's not on my NODE_PATH.
[root#uberneek ~]# which npm
/opt/bin/npm
[root#uberneek ~]# which node
/opt/bin/node
[root#uberneek ~]# echo $NODE_PATH
My NODE_PATH was empty, and running npm install --global --verbose promised-io showed that it was installing into /opt/lib/node_modules/promised-io:
[root#uberneek ~]# npm install --global --verbose promised-io
npm info it worked if it ends with ok
npm verb cli [ '/opt/bin/node',
npm verb cli '/opt/bin/npm',
npm verb cli 'install',
npm verb cli '--global',
npm verb cli '--verbose',
npm verb cli 'promised-io' ]
npm info using npm#1.1.45
npm info using node#v0.8.4
[cut]
npm info build /opt/lib/node_modules/promised-io
npm verb from cache /opt/lib/node_modules/promised-io/package.json
npm verb linkStuff [ true, '/opt/lib/node_modules', true, '/opt/lib/node_modules' ]
[cut]
My script fails on require('promised-io/promise'):
[neek#uberneek project]$ node buildscripts/stringsmerge.js
module.js:340
throw err;
^
Error: Cannot find module 'promised-io/promise'
at Function.Module._resolveFilename (module.js:338:15)
I probably installed node and npm from source using configure --prefix=/opt. I've no idea why this has made them incapable of finding installed modules. The fix for now is to point NODE_PATH at the right directory:
export NODE_PATH=/opt/lib/node_modules
My require('promised-io/promise') now succeeds.
add this to beginning of prog(mac):
module.paths.push('/usr/local/lib/node_modules');
By default node does not look inside the /usr/local/lib/node_module for loading global modules.
Refer the module loading explained in http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
So either you have to
1)add the /usr/local/lib/node_module to NODE_PATH and export it
or
2)copy the installed node modules to /usr/local/lib/node .
(As explained in the link for loading module node will search in this path and will work)
The following generic fix would for any module. For example with request-promise.
Replace
npm install request-promise --global
With
npm install request-promise --cli
worked (source) and also for globals and inherits
Also, try setting the environment variable
NODE_PATH=%AppData%\npm\node_modules
For some (like me) that nothing else worked, try this:
brew cleanup
brew link node
brew uninstall node
brew install node
Hope it helps someone :)
I got the "optimist" module error and I just did "npm install" to resolve it. went past that error.
https://github.com/mbloch/mapshaper/issues/12
On windows if you just did a clean install and you get this you need blow away your npm cache in \AppData\Roaming
$ vim /etc/profile.d/nodejs.sh
export NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
For Windows, from Nodejs cannot find installed module on Windows? what worked for me is running npm link as in
npm link wisp
I did this in simple way...
Un-Install node from control panel [Windows 7]
Install node again
Install protractor
npm install --global --verbose protractor
Update web driver manager.
works fine for me.
Hope this helps you....
I got this error Error: Cannot find module 'number-is-nan' whereas the module actually exists. It was due to a bad/incomplete Node.js installation.
For Windows , as other answers suggest it, you need a clean Node installation :
Uninstall Node.js
Delete the two folders npm and npm_cache in C:\Users\user\AppData\Roaming
Restart Windows and install Node.js
Run npm initor (npm init --yes for default config)
Set the Windows environment variable for NODE_PATH. This path is where your packages are installed. It's probably something likeNODE_PATH = C:\Users\user\node_modules or C:\Users\user\AppData\Roaming\npm\node_modules
Start a new cmd console and npm should work fine
Note :
Try the last points before reinstalling Node.js, it could save you some time and avoid to re-install all your packages.
For Mac User's It's Best use the manual installation:
To minimize the chance of permissions errors, you can configure npm to
use a different directory. In this example, it will be a hidden
directory on your home folder.
Back-up your computer before you start.
Make a directory for global installations:
mkdir ~/.npm-global
Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'
Open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH
Back on the command line, update your system variables:
source ~/.profile
Test: Download a package globally without using sudo.
npm install -g jshint
Instead of steps 2-4, you can use the corresponding ENV variable (e.g.
if you don't want to modify ~/.profile):
NPM_CONFIG_PREFIX=~/.npm-global
Reference : https://docs.npmjs.com/getting-started/fixing-npm-permissions
I have just met this problem of the axios module.
Then I tried this: run rm -rf node_modules and yarn.
And it works.
Had the same problem on one of the test servers running Ubuntu under root. Then created a new user using useradd -m myuser and installed everything (nvm, node, packages) as myuser. Now it's working fine.
In my case both node and npm were in same path (/usr/bin). The NODE_PATH was empty, so the npm placed the global modules into /usr/lib/node_modules where require(...) successfully find them.
The only exception was the npm module, which came with the nodejs package. Since I'm using 64 bit system, it was placed into /usr/lib64/node_modules. This is not where require(...) searches in case of empty NODE_PATH and node started from /usr/bin. So I had two options:
link /usr/lib64/node_modules/npm to /usr/lib/node_modules/npm
move modules from /usr/lib/node_modules/* to /usr/lib64/node_modules/ and set NODE_PATH=/usr/lib64/node_modules
Both worked. I'm using OpenSUSE 42.1 and the nodejs package from updates repository. Version is 4.4.5.
I had the same error as the OP, but digging through the logs I could see sh: node: command not found.
It turns out that the /usr/bin/node program (symlink) is no longer installed with apt install nodejs. Once symlinked /usr/bin/node' tonodejs,npm install -g #angular/cli` succeeded.
The proper way to install this on debian is apt install nodejs-legacy.
I had to add C:\Users\{Username}\AppData\Roaming\npm to my env variables and then i could install stuff.
Faced the same issue and got it resolved by adding the below line in my zshrc.
Based on your shell you can try adding in your rc file, for bash and zsh - bashrc/zshrc files present in your home location.
export NODE_PATH="/usr/local/lib/node_modules"
To directly add in zshrc file, run this command
echo 'export NODE_PATH="/usr/local/lib/node_modules"' >> ~/.zshrc
Alpine / Containerization
As mentioned elsewhere, the solution is to bake into your image,
NODE_PATH=/usr/local/lib/node_modules/
I've also opened up an issue upstream with npm apk so this gets set

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

I am trying to setup Node on Mac OSX Lion. It all seems to work ok, but I can't seem to import anything modules from my global modules folder. I get the error,
Error: Cannot find module <module>
If I run this: node -e require.paths, the response I get is:
[ '/usr/local/lib/node_modules',
'/Users/Me/.node_modules',
'/Users/Me/.node_libraries',
'/usr/local/Cellar/node/0.4.12/lib/node' ]
Which is correct, my modules are indeed installed in /usr/local/lib/node_modules. When I try and run a script, however, I am getting this:
Error: Cannot find module 'socket.io'
at Function._resolveFilename (module.js:326:11)
at Function._load (module.js:271:25)
at require (module.js:355:19)
at Object.<anonymous> (/Users/Me/node/server.js:2:10)
at Module._compile (module.js:411:26)
at Object..js (module.js:417:10)
at Module.load (module.js:343:31)
at Function._load (module.js:302:12)
at Array.<anonymous> (module.js:430:10)
at EventEmitter._tickCallback (node.js:126:26)
My .bash_profile looks like this:
export PATH=/usr/local/mysql/bin:$PATH
export NODE_PATH=/usr/local/lib/node_modules
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:/usr/local/mysql/lib/"
Would really appreciate some help, I have no idea why I can't import any libraries.
Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)
If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)
However, this doesn't come without its problems.
npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.
As an alternative, you can install the packages locally as well as globally.
For additional information, see
https://nodejs.org/en/blog/npm/npm-1-0-link/
https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/
You can use npm link to create a symbolic link to your global package in your projects folder.
Example:
$ npm install -g express
$ cd [local path]/project
$ npm link express
All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')
Install any package globally as below:
$ npm install -g replace // replace is one of the node module.
As this replace module is installed globally so if you see your node modules folder you would not see replace module there and so you can not use this package using require('replace').
because with require you can use only local modules which are present in your node module folder.
Now to use global module you should link it with node module path using below command.
$ npm link replace
Now go back and see your node module folder you could now be able to see replace module there and can use it with require('replace') in your application as it is linked with your local node module.
Pls let me know if any further clarification is needed.
You can use require with the path to the global module directory as an argument.
require('/path/to/global/node_modules/the_module');
On my mac, I use this:
require('/usr/local/lib/node_modules/the_module');
How to find where your global modules are? --> Where does npm install packages?
Setting the environment variable NODE_PATH to point to your global node_modules folder.
In Windows 7 or higher the path is something like %AppData%\npm\node_modules while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/ but it depends on user configuration.
The command npm config get prefix could help finding out which is the correct path.
In UNIX systems you can accomplish it with the following command:
export NODE_PATH=`npm config get prefix`/lib/node_modules/
Easy answer is to run node in npm global root directory.
cd $( npm root -g ) && node
I am using Docker. I am trying to create a docker image that has all of my node dependencies installed, but can use my local app directory at container run time (without polluting it with a node_modules directory or link). This causes problems in this scenario. My workaround is to require from the exact path where the module, e.g. require('/usr/local/lib/node_modules/socket.io')
If you are on windows cmd, you can do it via FOR /f "tokens=* delims=" %A in ('npm root --quiet -g') do set "NODE_PATH=%A" or FOR /f "tokens=* delims=" %%A in ('npm root --quiet -g') do set "NODE_PATH=%%A" in a batch file.
require.paths is deprecated.
Go to your project folder and type
npm install socket.io
that should install it in the local ./node_modules folder where node will look for it.
I keep my things like this:
cd ~/Sites/
mkdir sweetnodeproject
cd sweetnodeproject
npm install socket.io
Create an app.js file
// app.js
var socket = require('socket.io')
now run my app
node app.js
Make sure you're using npm >= 1.0 and node >= 4.0.

Resources