Search code examples
node.jsnpmweb3js

Nodejs - Cant import module unless use the full path


I installed it and am trying to use the w3 module (on windows).

I have altered my global repo location to: C:\Users\<user>\.node_modules_global and installed the web3 module with the command bellow, which created a new folder on the node_modules_global folder:

npm install ethereum/web3.js --global

When I try to run:

Web3 = require('web3') it, I get an

Error: Cannot find module 'web3'

however, if I use the fullpath:

Web3 = require('C:\\Users\\<user>\\.node_modules_global\\node_modules\\web3')

It works.

Any idea what could be causing this issue? (I have added C:\\Users\\<user>\\.node_modules_global to the SYSTEM PATH).


Solution

  • Your installing it globally, so it is saved to your user folder, rather than in the project, and node is configured by default to look in node_modules.

    Two options to fix this:

    • (a) Save Packages Locally Instead
      • Use just npm install ethereum/web3.js or npm install ethereum/web3.js --save to install it to the node_modules directory within your project. (You must have cd'd into your project folder first!)
    • (b) Make Node look in your global folders by default
      • use "NODE_PATH": "C:\\Users\\<user>\\.node_modules_global\\node_modules"

    How to install locally, and how to install globally

    • To locally install a module, just do npm install my-module, or if you'd also like to add it to your package.json, then do npm install my-module --save
    • To Globally install a module, use npm install my-module --global

    When to use local and global modules

    You should:

    • Install a module locally if you're going to require() it.
    • Install a module globally if you're going to run it on the command line.

    Source: https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/

    Changing Node path

    You can set the NODE_PATH environment variable to your own value, and your application will by default look there, instead of the projects node_modules directory.

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