Node - Cannot Find Module 'xml2js'
- Estimated read time: 3 min read
- Written by Chad Campbell on Sep 3rd 2013
You might've seen this error trying to run a Node app that loads an XML file. This error can be frustrating. Especially if you think you've installed this module correctly. This post will try to help you understand why and how to fix the Node "Cannot Find Module 'xml2js'" error. The first step in this process is understanding how Node looks for the 'xml2js' module.
Node starts looking for the 'xml2js' module in its core modules. The core modules can be found in the
lib directory in the Node source tree. The most recent list of core modules can be seen here. However, 'xml2js' isn't a core module. For that reason, Node will start looking elsewhere.
Node will start searching the local 'node_modules' directory for the 'xml2js' module. You can see which modules are locally installed by using the following command-line command:
If you prefer a Linux-style command-line command, you can use the following instead:
The last two commands do the same thing: they catalog the local packages (and their versions) in a tree structure. The packages are local to the directory the command-line command is ran in. If you do not see the 'xml2js' package in the tree structure, Node will begin going up the directory tree in search of 'xml2js'. This recursive climb will continue until the root is reached. If the 'xml2js' module is not in that path, Node will look at the globally installed modules. You can see those for yourself by using the following command-line command:
Here's some food for thought. When I started with Node, I thought I'd use the
node-xml2js module all the time. For that reason, I decided to install the module globally using
npm install -g xml2js. However, I learned that Node wasn't finding the globally installed package, even though it was listed when I used
npm list -global. I suspect this is because Node is still in its infancy at this point. Maybe there's another reason I'm not aware of. Still, I learned to just install packages local to each project for the time being.
I hope this helps you get past the "Cannot Find Module 'xml2js'" error. If you're still having challenges, I would encourage you to review the official modules documentation. If you found this post helpful, please consider giving us a +1. If you have any questions or comments related to this post, please leave them in the comments below. If you would like other help from Ecofic, please Contact Us.