Posted on by & filed under Content - Highlights and Reviews, Web Development.

Continuing the theme from a previous post, titled My First Time With Node.js, let’s suppose you’ve written a class that you want to test as part of a continuous integration build process using Node.js. How would you go about getting your class to a point that Node can test it?

Remember in the original article how I had a dumpme object and a requestHandler object? They looked something like this:

Suppose I had these declared in some external JavaScript file that was also used in the browser somewhere. If it’s my first time using Node.js, I might try just pulling in the external file using require:

And then I might try just accessing one of the objects from the file:

If I do that, I’m going to see something in the console log that looks like this:

This is because require expects that the file you are pulling in is a Node.js module, and it wants to expose things using syntax. You can get the file to work in Node.js if you do something like this:

And then export dumpme in the classdefs.js:

This will get you what you need, but if you then try to use classdefs.js in the browser, you’ll get an ‘exports is not defined’ error. Now you’ve just traded one problem for another!

Fortunately, you can have it both ways. All you need to do is check to see if exports has been defined and if not, create an empty object to hold it:

That will quiet the complaints in the browser, Node.js will stop hating your objects, and you can use your code in both places. You can take this even further, but if you aren’t ready to make big changes in your existing code just yet, this will get you going.

Safari Books Online has the content you need

Take advantage of these Node.js resources in Safari Books Online:

Node: Up and Running (Rough Cuts) introduces you to Node, the new web development framework written in JavaScript. You’ll learn hands-on how Node makes life easier for experienced JavaScript developers: not only can you work on the front end and back end in the same language, you’ll also have more flexibility in choosing how to divide application logic between client and server.
Read What Is Node? to get up to speed on Node.js with this concise overview.
Node for Front-End Developers shows you how to use this popular JavaScript framework to create simple server applications, communicate with the client, build dynamic pages, work with data, and tackle other tasks.
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.

Tags: Javascript, Node.js, object,

Comments are closed.