In My First Time With Node.js article I wrote an application using Node.js. Follow along if you’ve ever had troubles loading modules in Node.js.
If you’ve played with modules a little, you may have tried your hand at writing your own or installing one that didn’t use npm. At some point in the process, you might have come across some issues with Node not finding your module. Let’s look at what that’s like.
Suppose you’ve written a class to use in the browser, but you want to test it using Node.js as part of a continuous integration build process. If your class uses a browser construct – localStorage, for example – then you might see something like this when you try to run the test:
throw e; // process.nextTick error, or 'error' event on first tick
ReferenceError: localStorage is not defined
at Object. (/SOME/DIRECTORY/namesource.js:41:1)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)
Luckily, someone’s already written a localStorage implementation for Node.js, so all we have to do is pull that in and we should be good. You can install it using npm, but for the sake of argument, let’s say you didn’t.
If it’s your first time with Node.js, you might think you can just save the localStorage.js file to your working directory and include it using a normal required syntax:
var localStorage = require('localStorage');
That’s not going to do it. Your syntax is fine, but you’ll need to put the file where Node can find it, or tell Node where it is. That means putting it in the node_modules directory. In my case, when I installed the ws module using npm, a node_modules directory was created in my working directory. Meaning all I had to do was save localStorage.js into the ./node_modules directory.
You should now have a better understanding about modules in Node.js.
Safari Books Online has the content you need
Take advantage of these Node.js resources in Safari Books Online:
|Read What Is Node? to get up to speed on Node.js with this concise overview.|
|In Sams Teach Yourself node.js in 24 Hours, expert web developer George Ornbo guides readers through every step of creating custom server-side solutions with Node.js.|
About the Author
|Duane O’Brien is a tired computer scientist. He has written a number of articles on developing web applications and various PHP frameworks. To learn more about Duane, check out his blog or read his tweets.|