696

After pulling down a module from GitHub and following the instructions to build it, I try pulling it into an existing project using:

> npm install ../faye

This appears to do the trick:

> npm list
/home/dave/src/server
└─┬ faye@0.7.1
  ├── cookiejar@1.3.0
  ├── hiredis@0.1.13
  └── redis@0.7.1

But Node.js can't find the module:

> node app.js
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: Cannot find module 'faye'
    at Function._resolveFilename (module.js:334:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:357:17)
    at require (module.js:368:17)
    at Object.<anonymous> (/home/dave/src/server/app.js:2:12)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)

I really want to understand what is going on here, but I'm at a bit of a loss as to where to look next. Any suggestions?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dave Causey
  • 10,658
  • 7
  • 28
  • 26
  • 9
    The `node_modules` directory is expected to be in the root of your project, alongisde `app.js` in your case. Why did you use `..` the npm install path? – Alex Wayne Jan 26 '12 at 19:19
  • My intent was to have two directories - one for the faye sources from github and another one for my project that requires faye. By installing from the faye directory (../faye), I expected it would install the module locally under node_modules, which appears to be what happened. I don't want to install globally since there are other projects that depend on a stable version of faye. – Dave Causey Jan 26 '12 at 19:51
  • 1
    After changing "npm install ../faye" to "npm install ../faye/build", it works as expected. I don't know how typical this is, but faye creates a build directory when it is built and puts a copy of package.json in there. npm doesn't complain about package.json at the root level, but it references files that don't exist at that level. – Dave Causey Jan 26 '12 at 20:48
  • 2
    I solved the problem, but didn't really get any resolution to my real question, which was how to troubleshoot this issue. I'll try to come up with some suggestions for improving npm and/or node to make it easier for newcomers to avoid this situation. – Dave Causey Jan 26 '12 at 20:54
  • 1
    Go through this [Link](http://stackoverflow.com/questions/15471965/what-will-be-the-difference-in-requiremypackage-js-and-requiremypackage/15471995#15471995), you may get some idea like where exactly its failing to lookup your modules.. – Amol M Kulkarni Mar 18 '13 at 09:58
  • possible duplicate of [How do I import global modules in Node? I get "Error: Cannot find module "?](http://stackoverflow.com/questions/7970793/how-do-i-import-global-modules-in-node-i-get-error-cannot-find-module-module) – BuZZ-dEE Sep 23 '15 at 21:31
  • 1
    Check weather you are in the same folder where you installed it ? if you did not installed it globally . – Ashwani Panwar Jan 09 '19 at 08:59
  • Here is what I was doing incorrectly & spent my Friday afternoon, `const wpt = require("src/wpt");` which should have been `const wpt = require("./src/wpt");`. Path to the module or main JavaScript file was wrong. HTH someone. – Kumar Apr 17 '20 at 14:50

27 Answers27

570

Using npm install installs the module into the current directory only (in a subdirectory called node_modules). Is app.js located under home/dave/src/server/? If not and you want to use the module from any directory, you need to install it globally using npm install -g.

I usually install most packages locally so that they get checked in along with my project code.

Update (8/2019):

Nowadays you can use package-lock.json file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the package-lock.json tracks the exact versions of your node_modules, you're currently using. To install packages from package-lock.json instead of package.json use the command npm ci.

Update (3/2016):

I've received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (https://kodfabrik.com/journal/i-ve-just-liberated-my-modules) which broke React, Babel, and just about everything else. Hopefully it's clear now that if you have production code, you can't rely on NPM actually maintaining your dependencies for you.

Charles Bamford
  • 831
  • 1
  • 15
Bill
  • 23,603
  • 7
  • 86
  • 119
  • 269
    "I usually install most packages locally so that they get checked in along with my project code." It's usually better to make a `package.json` listing what npm modules you depend on and ignore the `node_modules` folder. Then simply `npm install` to get setup after you clone the repo. – Alex Wayne Jan 26 '12 at 19:20
  • 59
    In addition to `package.json` listing the dependencies, I like to keep known good copies of things that I depend on. Disk space is cheap and if npm or the package disappears from npm, I'll still have a fully working project in my repo. – Bill Jan 26 '12 at 20:02
  • Thanks for the replies. All I'm trying to do is try out a development version of the module from github without installing it globally. Both app.js and node_modules are under /home/dave/src/server. I'll try the package.json approach, but I was hoping to figure out what exactly I am doing wrong above so other people don't repeat my mistake. – Dave Causey Jan 26 '12 at 20:08
  • Using package.json won't change anything. If they are in the same directory and it's still not resolving then we'll need to see the code. Either the way you are importing it is incorrect or the way the module is exporting is incorrect. – Bill Jan 26 '12 at 20:32
  • 3
    I figured out what I was doing wrong. After changing "npm install ../faye" to "npm install ../faye/build", it works as expected. I don't know how typical this is, but faye creates a build directory when it is built and puts a copy of package.json in there. npm doesn't complain about package.json at the root level, but it references files that don't exist at that level. – Dave Causey Jan 26 '12 at 20:40
  • 177
    As an old developer I nearly choked when I read the Node devs "paradigm" that "disk space is cheap". I have libraries that I am using. The idea that I might have 100 copies (or worse, NEAR copies) makes my stomach turn. Disk space is cheap, but maintenance time is expensive. Perhaps if you are doing a one-off toy project, maintenance is cheap. For real work, however, maintenance is expensive and has no bearing on the cost of disk space. – Lloyd Sargent Jan 30 '14 at 16:26
  • 77
    I really don't understand this last comment. Nobody is saying to have 100 copies of any piece of code, just to have 1 copy of the code that your project depends on. The alternative is to have a non-functional project if NPM or the dependency disappears one day. I would think re-writing a dependency from scratch is also pretty expensive. As an aside, I worked at Microsoft for 10 years and we always had 3rd party dependencies checked into our source tree. – Bill Jun 09 '14 at 17:32
  • 39
    @LloydSargent Having "NEAR copies" *isn't* worse, it's *better*, because each project has a specific dependency, that you've defined, and the rest of your code relies on. If you had the *same* versions across multiple projects then if you update *anything* you *must* update *everything*. Pinning dependencies allows piecemeal upgrades-substantially *less* maintenance. Real work, non-toy projects. – Dave Newton Aug 07 '14 at 17:40
  • 4
    @DaveNewton Yes. This is what the Node developers are saying: disk space is cheap, therefore copy the code library across multiple projects. They totally skip the part that if the library is updated those multiple copies must be updated. That was the point of my post. – Lloyd Sargent Aug 17 '14 at 00:37
  • `npm` is primarily a dev tool. If the project is working, there is no reason to update the libraries upon which it depends. If you're doing long-term maintenance of production environments, `npm` is not the tool to use. `apt` might be better for that. – Jess Austin Sep 22 '14 at 03:03
  • 1
    @Bill- node allows for a rather inefficient way of organizing modules, which npm abuses to regularly create extremely deep and redundant nesting of modules dependencies. For any module, that module's dependencies may exist either at the same level as the module, or in a directory in the module, typically called `node_modules`. So, if you have 5 modules listed in your package.json and each depends on (or has a dependency which depends on) any other particular package, npm's default behaviour is to install a copy of the dependency under each of the module's node_modules directory. – bschlueter Oct 19 '14 at 07:25
  • @bschlueter I find using the --production flag cuts out most of the redundancy (most of the deep nestings are for the dev tools that surround a project). But in any case, this is the system that npm uses so the options are still to check it all in so you can always rebuild, or hope the versions that you need remain forever available on npm. – Bill Oct 19 '14 at 07:36
  • @Bill My problem isn't with the fact that all the modules get stored, it's that they may be stored multiple times. It seems to me that each version of each module could all be stored at the same level in one directory, which would make the deep paths unnecessary. Ruby and Python both do this, and it produces a much cleaner module directory. – bschlueter Oct 19 '14 at 18:54
  • @bschlueter Totally agree that it's not the best system and could have been designed to be more efficient, but it's what we're currently stuck with. – Bill Oct 19 '14 at 20:04
  • 2
    npm shrinkwrap I believe it is will make sure that, if node modules are ignored in version control(git), the version of all dependencies in the project stay consistent and it will always use the version that was used originally, and is working, in the project when running npm install on another machine to work on the project. – mikeLspohn Dec 10 '14 at 05:54
  • I don't see why you should check in the installed packages? I would suggest that you **only** check in the actual file that states which packages to install. – Cyclonecode Mar 21 '16 at 11:08
  • 15
    Because of this: https://medium.com/@azerbike/i-ve-just-liberated-my-modules-9045c06be67c#.kq9s64clp. Somebody went and unpublished all of their modules. My builds were all fine, how did everyone else fair? – Bill Mar 23 '16 at 23:41
  • 7
    @Bill, I couldn't agree more with your policy. The popularity of some of the counter-responses is very troubling. My idea of revision control doesn't involve making assumptions about the future actions of unknown third parties. – Dave Causey Apr 13 '16 at 20:40
  • 1
    Maybe a bit late to the party but, Bill is right. It is just tedious. A middle ground approach is to develop, based on NPM (meaning, not committing the libraries) for development and having developers use NPM. Then for production, moving "release" packages, meaning, including all the dependencies. Releasing via GIT and expecting NPM to manage dependencies is not a good practice. – smorhaim Aug 08 '16 at 19:28
  • Nowadays you can simply use a shrinkwrap and have a package-lock.json to specify your production dependencies, and allow your normal package.json to call the shots in dev environments. Then, just periodically update your package-lock.json once you know for sure that current versions of you packages work (since you've fleshed them out locally over time). – Richard Pressler Feb 27 '18 at 20:04
508

I had a very similar issue. Removing the entire node_modules folder and re-installing worked for me:

rm -rf node_modules
npm install
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Abhinav Singh
  • 6,884
  • 1
  • 20
  • 31
94
npm install --save module_name

For example, if the error is:

{ [Error: Cannot find module '/root/.npm/form-data'] code: 'MODULE_NOT_FOUND' }

then you can resolve this issue by executing the command npm install --save form-data.

bruntime
  • 371
  • 2
  • 12
Piyush Chordia
  • 1,205
  • 9
  • 7
  • 1
    it seems like when i installed it globally the npm/node-modules folder was empty and i was trying to use `ng new project-name` it was showing some modules missing ... I had to install them each using the given command.Then it solved the issue but is there any single command to install all of the them at once ? – Vishal Nair Jun 24 '16 at 07:06
  • Thank You! This solution worked for me when node-sass-chokidar could not be found when trying to run a react project. – Benjamin John Jun 16 '20 at 13:59
27

For TypeScript users, if you are importing a built-in Node module (such as http, path or url) and you are getting an error such as "Cannot find module "x" then the error can be fixed by running

npm install @types/node --save-dev

The command will import the NodeJS TypeScript definitions into your project, allowing you to use Node's built-in modules.

mgthomas99
  • 2,960
  • 1
  • 16
  • 20
20

This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted. Trying an npm install again won't save the problem.

Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alex Werner
  • 310
  • 3
  • 8
  • 18
    this diagnosed the problem for me. i ended up doing `npm cache clear` and clearing out node_modules followed by `npm install` to fix my issue. – meklarian Oct 15 '15 at 19:44
11

If you use nvm, check that existing node_modules that are bindings to other libraries are compiled for the correct Node.js version.

I was having the same error. The reason was the following: We use nvm since we're running two apps on a server, one requires Node.js 5.6 because it uses node-gd (which doesn't run on Node.js 6 for now), the other requires Node.js 6. Node.js 6 is the apt-get installation.

Also we use the pm2 tool to deploy.

So, the default setup is that the pm2 process starts when nvm is not in effect, so it uses the apt-get installation of Node.js (version 6). So the main pm2 daemon starts with Node.js 6. If I run applications in fork mode they start in separate processes and nvm settings are in effect. When I run applications in cluster mode - they inherit the non-nvm environment.

So when I tried to switch to the cluster mode the application failed to start because the bindings compiled for 5.6 fail with this message.

I've fixed that by restarting pm2 when nvm setings are in effect. Also startup scripts should be fixed.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ilya Sheershoff
  • 339
  • 3
  • 10
10

I experienced this error yesterday. Took me a while to realise that the main entry in package.json was pointing to a file that I'd moved. Once I updated that the error disappeared and the package worked.

ukosteopath
  • 343
  • 5
  • 14
  • 3
    Holy cow...out of desperation I typed in "Error: Cannot find module" into google, and found this question. Your answer fixed my problem. I can't believe such a vague search term turned up the right answer. Kudos to you and to Google! – Jamon Holmgren Dec 21 '17 at 10:00
  • 2
    Very much this. I had managed to point the `main` entry for my submodule in a directory that was excluded from its repository so when I tried to include it via `npm install` it worked, but no exports were found when required in! Many thanks for this obvious but useful answer. – Dragos Feb 26 '19 at 11:13
  • 1
    Thanks for this. I had this situation whilst using Yarn workspaces, so was looking all over for path resolution algorithms and all sorts. :) I was thrown by the way the error message talks of 'locating' the module, and also that ESLint was giving similar error messages. And then I saw your answer and realised I was a dimwit. Thanks! – Mark Birbeck Sep 17 '19 at 10:37
9

Check if the enviroment variable NODE_PATH is set correctly and pointing to the node_modules path. nodejs uses this variable to search for the libraries

Edgar Chavolla
  • 626
  • 8
  • 4
  • I upvoted this as it solved my immediate problem, and led me to [this node.js documentation](https://nodejs.org/api/modules.html#modules_all_together). But I think this is not a blanket answer, as the documentation indicates alternative strategies for locating modules. – Graham Klyne Feb 07 '19 at 15:53
6

This error can be encountered if you are requireing a module that has a missing or incorrect main field in its package.json. Though the module itself is installed, npm/node has to use a single .js file as an entrypoint to your module. If the main field is not there, it defaults to looking for index.js in your module's folder. If your module's main file is not called index.js, it won't be able to require it.

Discovered while turning a browserify-based module into a CommonJS require-able module; browserify didn't care about the missing main field, and so the error had gone unnoticed.

MrCranky
  • 1,452
  • 22
  • 30
4

Remove your node_module root folder from your project(eg: myApp). Go to myApp folder and then type below command from terminal

>myApp>npm install

It will install all the dependency modules required for your project.

  • Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Jul 06 '16 at 07:45
4

Specify the path to the restler folder, which will be inside node_modules folder like : var rest = require('./node_modules/restler');

This worked for me.

4

If all other methods are not working for you... Try

npm link package_name

e.g

npm link webpack
npm link autoprefixer

e.t.c

james ace
  • 645
  • 6
  • 5
3

I can add one more place to check; the package that I was trying to use was another one of my own packages that I had published to a private NPM repo. I had forgotten to configure the 'main' property in the package.json properly. So, the package was there in the node_modules folder of the consuming package, but I was getting "cannot find module". Took me a few minutes to realise my blunder. :-(

martinp999
  • 359
  • 5
  • 8
3

If you are using typescript and getting an error after installing all node modules then remove package-lock.json. And then run npm install.

Kartik Garasia
  • 964
  • 1
  • 13
  • 21
3
rm package-lock.json
rm -r node_modules
npm i

That should fix issue and install all packages.

Xakiru
  • 1,631
  • 1
  • 10
  • 9
2

PRO TIP:

This error happened to me, while fighting fatigue and mild illness, because I typed node blah instead of npm blah.

The error message received wasn't angry enough to alert me to my own folly!

Dave
  • 2,449
  • 26
  • 30
2

I faced the same problem when someone else in the team updated package.json in SVN. Merely removing the node_modules directory did not help. How I solved the problem is:

rm -rf node_modules
rm package.json
rm package-lock.json
svn up
npm install
ng build --env=prod

Hope this helps someone!

Soumya Kanti
  • 1,389
  • 1
  • 17
  • 28
  • Thanks for the reminder. In my case it was package-lock.json messing things up again but after deleting it and node_modules then running `npm install` all is well again. – TaeKwonJoe Feb 01 '19 at 07:29
  • 18
    If you remove `package.json` how does NPM know what to install? – Michał Sep 23 '19 at 14:31
1

I was trying to publish my own package and then include it in another project. I had that issue because of how I've built the first module. Im using ES2015 export to create the module, e.g lets say the module looks like that:

export default function(who = 'world'){
    return `Hello ${who}`;
}

After compiled with Babel and before been published:

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

exports.default = function () {
    var who = arguments.length <= 0 || arguments[0] === undefined ? 'world' : arguments[0];


    return 'Hello ' + who;
};

So after npm install module-name in another project (none ES2015) i had to do

var hello = require('module-name').default;

To actually got the package imported.

Hope that helps!

Belgor
  • 183
  • 1
  • 2
  • 9
1

Just found an unusual scenario that may be of use to someone and is sort of a red herring.

I was also getting the Cannot Find Module error but oddly everything worked perfectly in my local (Mac hosted) Node.js environment. This problem only appeared when the code was deployed on our Linux server.

Well... it turned out to be a typo that (apparently) the Mac based Node.js installation was perfectly happy to ignore.

The include looked like this:

var S3Uploader = require('./S3Uploader.class');

But the actual file was called "s3Uploader.class.js"

Notice the casing difference in the 's' vs. 'S' between the code and the filename.

So - in the odd chance that none of the other solutions here are solving your problem, triple check that you're not mis-casing the characters in your included filename! :)

and DUH!

Yevgeny Simkin
  • 26,055
  • 37
  • 127
  • 228
  • 2
    By default osx filesystem (HFS+) is [case insensitive](https://apple.stackexchange.com/questions/22297/is-bash-in-osx-case-insensitive) ... discovered not long ago, it's definitely configurable though – giulp Nov 22 '17 at 10:04
1

In my case I had UNMET PEER DEPENDENCY redux@^3.0.0 causing this error message, see all of them and install missing modules again using --save

npm install redux --save
Ursu Alexandr
  • 168
  • 1
  • 8
1

Removing node/npm and then re-installing the stable(not the latest) version worked for me.

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

https://nodejs.org/en/download/
Kal
  • 153
  • 3
  • 12
1

I had this issue using live-server (using the Fullstack React book):

I kept getting:

Error: Cannot find module './disable-browser-cache.js' 
...

I had to tweak my package.json

  • From:

    "scripts": { ... "server": "live-server public --host=localhost --port=3000 --middleware=./disable-browser-cache.js" ... } "scripts": {

  • To:

    ... "server": "live-server public --host=localhost --port=3000 --middleware=../../disable-browser-cache.js" ... }

Notice relative paths seem broken/awkward... ./ becomes ../../

I found the issue here

Also if anyone follows along with that book:

  1. change devDependencies in packages.json to:

"live-server": "https://github.com/tapio/live-server/tarball/master"

Currently that upgrades from v1.2.0 to v1.2.1

  1. It's good to use nvm.
  2. It's best to install v13.14 of Node (*v14+ creates other headaches) nvm install v13.14.0
  3. nvm alias default v13.14.0
  4. Update npm with npm i -g npm@7.3.0
  5. run: npm update
  6. you can use npm list to see the hierarchy of dependencies too. (For some reason node 15 + latest npm defaults to only showing first level of depth - a la package.json. That renders default command pointless! You can append --depth=n) to make command more useful again).
  7. you can use npm audit too. There issues requiring (update of chokidar and some others packages) to newer versions. live-server hasn't been updated to support the newer corresponding node v 14 library versions.

See similar post here


Footnote: Another thing when you get to the JSX section, check out my answer here: https://stackoverflow.com/a/65430910/495157

When you get to:

  • Advanced Component Configuration with props, state, and children. P182+, node version 13 isn't supported for some of the dependencies there.
  • Will add findings for that later too.
JGFMK
  • 7,107
  • 4
  • 46
  • 80
0

Encountered this problem while using webpack with webpack-dev-middleware.

Had turned a single file into a folder.

The watcher seemed to not see the new folder and the module was now missing.

Fixed by restarting the process.

Chris
  • 2,636
  • 1
  • 25
  • 33
0

Maybe like me you set 'view engine' in express to an engine that doesn't exist, or tried to use an unregistered templating engine. Make sure that you use: app.engine('engine name',engine) app.set('view engine','engine name')

0

Please install the new CLI v3 (npm install -g ionic@latest).

If this issue is still a problem in CLI v3. Thank you!

Akash Limbani
  • 808
  • 2
  • 7
  • 28
-3

First of all, yes, a part of my answer definitely is helpful to solve the error that is posted by OP. Secondly, after trying the below step, I faced a couple of other errors, and so, have written the solution of those too.

(Psst! I am not sure if I've successfully helped in solving the above error, or if I've broken some rule or format of answering, but I faced the above error and some others and it took much time for me to find the proper solutions for those errors. I'm writing the complete solution because in case, if someone else also faces these errors, then he'll hopefully get a solution here.)

So adding to, and elaborating the answer provided by PrashanthiDevi, and also adding my personal experience, here it is:

I am new to the whole e2e and unit tests part. I started looking into this part from Protractor. Now I already had the files in which tests were written, but I had to run the tests.

I had already installed all the required softwares and tools, but when I initially ran the code for running the tests, gulp itest, I got this 'Cannot find module' Error. After going through many different questions on SO, I found one answer that I thought could help getting a solution.

The person had suggested to run the command npm install in my project folder.

The reason for doing this was to update the node-modules folder, inside our project folder, with all the required and necessary files and dependencies.

(The below part maybe irrelevant with this question, but might be helpful if anyone came across the same situation that I faced.)

The above step surely solved my previous error, but threw a new one! This time the error being Could not find chromedriver at '..\node_modules\protractor\selenium\chromedriver'.

However, the solution of this error was pretty silly (and funny) to me. I already had the chromedriver file in my selenium folder. But, turns out that the above error was coming because my chromedriver files were inside selenium folder and not inside chromedriver folder. So, creating a chromedriver folder and copying the chromedriver files there solved my problem!

Also, for the error: Timed out waiting for the WebDriver Server, you could add this line of code to conf.js file inside exports.config{}:

seleniumAddress: 'http://localhost:8080/'

Hope this helps!

Community
  • 1
  • 1
HardikT
  • 675
  • 1
  • 7
  • 22
-34

Change the directory and point to your current project folder and then "npm install". .

This will install all dependencies and modules into your project folder.

emekaokoli
  • 49
  • 2
  • 9