Saturday, November 10, 2012

Hello world with nodejs and script#

I have used S# at work before to write client side javascript. It really shines when you have a lot of javascript files/modules in your application. You get all the benefit of leveraging C# oops paradigm, managing dependencies among various modules in javascript as well as benefiting from all the tools Visual studio has to offers.

Recently, I was playing with nodejs in one of my project and wanted to see if I can build a simple Hello World nodejs application with S#. Even though the public version of S# extension for Visual Studio does not support NodeJs out of the box, the functionality already exists as part of S# github repository. So to get started, I need the latest bits from S# github repository. To do so, 


1. Clone the repository


git clone https://github.com/nikhilk/scriptsharp.git

2. Once its cloned, go to scriptsharp/src folder and open ScriptSharp.sln solution. Now build the solution with both debug and release setting.

3. Once done, go back to scriptsharp root folder. At this point, you should see a bin folder containing following folders.




4. At the time of writing, this should corresponds to 0.8 version of S#. Simply double click on ScriptSharp extension and install it. As a best practice, I always keep a copy of the whole folder under my external libraries folder and add a README file to note the time stamp when I build this library.


5. Once the extension is installed, create a new project in visual studio and select nodejs application as follows:





6. You project should now contain a single class (Class1.cs) which essentially creates a program that listens to all the http requests on your localhost at port 1337 and spits "Hello Node.js World, from Script#!" in response.

7. To run this program, simply build it, It will output <yourappname>.js file in bin folder. Navigate to the either bin/debug or bin/release (depending on how you build your app) folder in your command prompt and simply run 


node <youappname>.js

Now navigate to http://127.0.0.1:1337/ and you can see your Hello World program in action.


NOTE: For some reason port 1337 did not work for me. When I ran node command from command line , I got:



events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: listen EACCES
    at errnoException (net.js:769:11)
    at Server._listen2 (net.js:892:19)
    at listen (net.js:936:10)
    at Server.listen (net.js:993:9)
    at dns.js:71:18
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

To get rid of this error, I simply changed the port to 1338 and it started working for me. I am not sure why it is throwing that error. My guess is I have some other service running on that port.


As I mentioned before, though the power of S# might not seem obvious with this Hello world example, but I am sure that as you app logic grows, you will appreciate the power of S#.

No comments: