Tuesday, 20 August 2013

Error: Cannot find module

I ran into this little node.js problem today. 
Error: Cannot find module 'autoloader'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (c:\node\web\auto\test.js:1:63)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)

Was trying to use a package call autoloader. It installed fine but when I would try and run my node.js code. Bang, would get the above error.

This turned out to be a noob mistake on my part.
Fix: you can install a node package from any directory but to have it seen by node.js you need to install it while in the node directory.

  1. Navigate to wear your node executable is.
  2. Install your package as normal.. Done!

While I'm here I might as well talk a little bit more about installing packages(more commonly known as libraries). There are 3 things to know.
  • What: So node.js has a very minimalist belief where anything additionally that you need can just be installed. To this end there is the node package manager(npm). This is the best source to find and install packages for pretty much everything you could imagine to do with node.js/javascript. 
  • Where: Now, as with my above problem. If you run something like  npm install autoloader  it will create a directory called node_modules(if it does not exist already), download the library autoloader and install it into a subdirectory under node_modules. This is great but remember you need to be in the node.js directory so you ;node_modules are all in the same place so the node.js execute can find them. (This is also referred to as installing locally)
  • Global: There is an additional parameter in particular -g that can allow you to use the libraries from anyway where via your terminal. It does this by adding a path to the package in your environmental variables. The above autoloader example would then look like   npm install autoloader -g  

No comments:

Post a Comment