Monday 27 February 2012

simple node.js module

Recently, I've been looking at node.js just to see something completely different than .NET.  In doing so, I'm building a small web application on top of express with jade.  Disclaimer: I'm not a javascript developer.  So, this for me is about both learning more about javascript and checking out alternative technologies.

I recently wanted to format a date in node.js like this: dd/MM/yyyy hh:ss.  There may be a better way to do it, but I decided to create a dateFormatter.js module so that I could see how to reuse some javascript code in node.js.

My first thought was that I needed to expose a new javascript object DateFormatter with the method format(d). Makes sense right?

So I set off by creating a file named dateFormatter.js that looked something like this:

And no, it didn't run at all.  Like I said, not great at using javascript in an OOP way!

What I didn't understand was that modules in node.js are wrapped as objects for you.

So by using the exports. I was really defining the public interface of my object.  So, I changed the code to this:

And then I reference and use it like this:

At the moment, this works for me.

No comments:

Post a Comment