简体   繁体   中英

Nodejs Cannot find module

I'm getting an error when trying to use any global module, exemple:

Error: Cannot find module 'express'
    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> (C:\BitNami\wappstack\...\test\app.js)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)

I installed the express command:

npm install -g express

My app.js:

var express = require('express');

And run it using windows powershell or node.js command prompt windows:

node app.js

do not really know what's going wrong, I read something about environment variables in windows, can this be?

Resolved / Update

The problem was: Windows environment variables was not configured for npm folder. Search for your npm folder and add the path in the environment variables.

Just to quote from here:

https://www.npmjs.org/doc/files/npm-folders.html

  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line.
  • If you need both, then install it in both places, or use npm link .

You should install Express locally:

npm install express

Then require it as you did:

var express = require('express')

I was getting same error on Windows7/x64 and adding following in the environment variable resolved the issue:

NODE_PATH=C:\Users\[USERNAME]\AppData\Roaming\npm\node_modules

*Replace [USERNAME] with your actual system username

I'm working in Linux, but when I require express, I'm doing so with a relative path to where it is installed and it works fine:

var express = require('./public/node_modules/express');

I'm sure the same thing would work with a windows path as well. If you want to be more explicit and declare an absolute path, that would be the nuclear option to make sure you always know exactly where your module is being loaded from regardless of where your scripts are being run from.

If you still have a problem after using an explicit path, I don't know what the problem might be. . .

另一个选择是运行npm install --save express

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM