How do I resolve Cannot find module error using Node.js?

How do I resolve Cannot find module error using Node.js?

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, youre currently using. To install packages from package-lock.json instead of package.json use the command npm ci.

Update (3/2016):

Ive 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 its clear now that if you have production code, you cant rely on NPM actually maintaining your dependencies for you.

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

rm -rf node_modules
npm install

How do I resolve Cannot find module error using Node.js?

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.

Leave a Reply

Your email address will not be published.