简体   繁体   中英

node.js require function not finding module

I have a server.js file that I downloaded from someone's website. The first line is: var express=require('express');

When I try to run this server with "node server.js" I get the following error: "Cannot find module 'express'." The express module is installed in the default node install location:

C:\\Users\\myname\\node_modules\\express\\

I'm able to successfully run express by executing "node express.js" from the express install location in node_modules. I also tried copying over the express folder and file into my c:\\node-testing\\ directory where my server.js file is located but I still get the error. Any idea what the problem might be and how to fix?

Node.js will only search for modules in from the current (and parent) directories. Unlike npm, Node has no concept of "global" modules.

You need to run npm install to install your modules into the directory containing your code.

You can set the NODE_PATH environment variable to tell nodejs to search other paths for globally installed modules that are not in the project directory.

See http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders for details.

On Unix installations there are some built-in default locations, but on Windows, it appears you have to set this environment variable manually to support a global location.


FYI, if you want require to load a module from the project directory, then you have to use

require("./filename");

with the ./ in front of it. That's why it didn't work when you copied it to the project directory. node makes a distinction between loading from the project directory vs. loading from the node_modules directory below and thus requires a different syntax to specify which one you want. Express.js is also not a stand-alone module because it depends on a bunch of other modules so you could not copy only it. I'd recommend using the NODE_PATH option or install express into your project directory (it will end up in a node_modules sub-directory).

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