WebStorm JavaScripting & Noding Workflow Webinar Recording

Today the JetBrains team wrapping up final processing for my webinar from last week. You can check out the webinar via their JetBrains Youtube Channel:

JavaScriptFor even more information be sure to check out the questions and answers on the JetBrain WebStorm IDE blog entry. Some of the questions include:

  • Q: How to enable Node.js support in PhpStorm (PyCharm, IntelliJ IDEA, RubyMine)?
  • Q:How to enable autocompletion for Express, Mocha and other libraries?
  • Q: Is it possible to debug a Node.js application that runs remotely? Is it possible to debug when your node and the rest of the dependencies (database, etc.) are running in a VM environment like Vagrant?
  • Q: Does the debugger support cluster mode?

…and others all here.

Some JavaScript API Coding With Restify & Express & Hacking it With cURL …Segment #2

Ah, part 2! If you’re looking for part 1, click this link.

Review: In the last blog entry I went through more than a few examples of using cURL to issue GET requests against various end points using Node.js & Restify. I also covered the basics on where to go to find cURL in case it isn’t installed. The last part I covered was a little bit of WebStorm info to boot. In this part of the series I’m now going to dive into the HTTP verbs beyond GET.

POST

The practice around issuing a command via http verb to save data is via a post. When you issue a post via cURL use the -X followed by POST to designate a post verb, then -H to assign the content type parameter. In this particular example I’ve set it to application/json since my payload of data will be JSON format. Then add the final data with a -d option, followed by the actual data.

curl -X POST -H "Content-Type: application/json" -d '{"uuid":"79E5591A-1E54-4562-A276-AFC266F54390","webid":"56E62C3A-D6BC-4F4F-B72A-E6CE081190B6"}' http://localhost:3000/ident

Other data types can be sent, which the content type can be appropriately set for including; html, json, script, text or html. One example of this same command, issued with jQuery on the client side would actually look like this.

var data = {"uuid":"79E5591A-1E54-4562-A276-AFC266F54390","webid":"56E62C3A-D6BC-4F4F-B72A-E6CE081190B6"};

$.post( "http://localhost:3000/ident", function( data ) {
  $( ".result" ).html( data );
});

When building post end points via express one of the things you may run into is the following message being displayed in the console.

/usr/local/bin/node app.js
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

The immediate fix for this, until the changes are made (which may or may not mean to just alwasy  is to replace this line

app.use(express.bodyParser());

with these lines

app.use(express.json());
app.use(express.urlencoded());

So here’s some common examples for use from a great write up on writing basic RESTful APIs with Node.js and Express from the Modulus blog.

var express = require('express');
var app = express();

app.use(express.json());
app.use(express.urlencoded());

var quotes = [
    { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
    { author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
    { author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
    { author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];

app.get('/', function(req, res) {
    res.json(quotes);
});

app.get('/quote/random', function(req, res) {
    var id = Math.floor(Math.random() * quotes.length);
    var q = quotes[id];
    res.json(q);
});

app.get('/quote/:id', function(req, res) {
    if(quotes.length <= req.params.id || req.params.id < 0) {
        res.statusCode = 404;
        return res.send('Error 404: No quote found');
    }

    var q = quotes[req.params.id];
    res.json(q);
});

app.post('/quote', function(req, res) {
    if(!req.body.hasOwnProperty('author') ||
        !req.body.hasOwnProperty('text')) {
        res.statusCode = 400;
        return res.send('Error 400: Post syntax incorrect.');
    }

    var newQuote = {
        author : req.body.author,
        text : req.body.text
    };

    quotes.push(newQuote);
    res.json(true);
});

app.listen(process.env.PORT || 3412);

This is a great little snippet of code to use for testing your curling against just to check out.

References:

Some JavaScript API Coding With Restify & Express & Hacking it With cURL …Segment #1 (with some Webstorm to boot)

So often I end up putting together some RESTful services (or the intent is to at least build them with that premise, but we all know how that ends up). The API URIs routing gets put together and one wants to take a crack at the service as soon as possible. Here’s a quick guide for using cURL to take some basic actions against the services and understand what you’re getting back.

The first thing to do is make sure you can run JavaScript, which means you have a computer. The second thing is to get cURL, which means you’re running some variant of Linux or UNIX. In most scenarios one would be running OS-X. The easiest way to determine if it is installed on your computer just open up a terminal and type ‘curl –help’. You should get a result with all the switches, which is almost always a bit of overload.

$ curl --help
Usage: curl [options...]
Options: (H) means HTTP/HTTPS only, (F) means FTP only
     --anyauth       Pick "any" authentication method (H)
 -a, --append        Append to target file when uploading (F/SFTP)
     --basic         Use HTTP Basic Authentication (H)
     --cacert FILE   CA certificate to verify peer against (SSL)
     --capath DIR    CA directory to verify peer against (SSL)
 -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)
     --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)
     --ciphers LIST  SSL ciphers to use (SSL)
     --compressed    Request compressed response (using deflate or gzip)
 -K, --config FILE   Specify which config file to read
     --connect-timeout SECONDS  Maximum time allowed for connection
 -C, --continue-at OFFSET  Resumed transfer offset
 -b, --cookie STRING/FILE  String or file to read cookies from (H)
 -c, --cookie-jar FILE  Write cookies to this file after operation (H)
     --create-dirs   Create necessary local directory hierarchy
     --crlf          Convert LF to CRLF in upload
     --crlfile FILE  Get a CRL list in PEM format from the given file
 -d, --data DATA     HTTP POST data (H)
     --data-ascii DATA  HTTP POST ASCII data (H)
     --data-binary DATA  HTTP POST binary data (H)
     --data-urlencode DATA  HTTP POST data url encoded (H)
     --delegation STRING GSS-API delegation permission
     --digest        Use HTTP Digest Authentication (H)
     --disable-eprt  Inhibit using EPRT or LPRT (F)
     --disable-epsv  Inhibit using EPSV (F)
 -D, --dump-header FILE  Write the headers to this file
     --egd-file FILE  EGD socket path for random data (SSL)
     --engine ENGINE  Crypto engine (SSL). "--engine list" for list
 -f, --fail          Fail silently (no output at all) on HTTP errors (H)
 -F, --form CONTENT  Specify HTTP multipart POST data (H)
     --form-string STRING  Specify HTTP multipart POST data (H)
     --ftp-account DATA  Account data string (F)
     --ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)
     --ftp-create-dirs  Create the remote dirs if not present (F)
     --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)
     --ftp-pasv      Use PASV/EPSV instead of PORT (F)
 -P, --ftp-port ADR  Use PORT with given address instead of PASV (F)
     --ftp-skip-pasv-ip Skip the IP address for PASV (F)
     --ftp-pret      Send PRET before PASV (for drftpd) (F)
     --ftp-ssl-ccc   Send CCC after authenticating (F)
     --ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)
     --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)
 -G, --get           Send the -d data with a HTTP GET (H)...

Don’t get intimidated! It goes on and on and on, but just know it’s installed if you see all these goodies. If you don’t get the results above, then installing cURL is the next step. I’ll leave that to you. Here’s some links to download and get started however.

Next you’ll of course need Node.js and Restify installed. I’ll assume you have Node.js installed. Create a directory and in that directory just run the following command.

npm install restify

Next create a file called server.js in that directory you’ve just installed restify in. Here’s the initial JavaScript code for that file that I’ve used to put together for the first few examples of using cURL.

var restify = require('restify');

function respond(req, res, next) {
    res.send('hello ' + req.params.name);
}

var server = restify.createServer();
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

Ok, now to run this with node.js just issue the command to launch node.js with this file that was just created.

node server.js
restify listening at http://0.0.0.0:8080

Getting Get

Now the service is running on port 8080 against 0.0.0.0. To check out what a standard GET verb will do in a browser, open up a browser and navigate to http://0.0.0.0:8080.

Browsing the GET response via Chrome.

Browsing the GET response via Chrome.

You’ll see this in the browser window. Just straight plain text too. If you look at source, this is all you get back. Now open up a terminal and run the following cURL command to execute a GET against the URI & port. This is the most basic cURL command one can make. It is simply issuing a GET request against the URI and will display the body of the response.

curl 0.0.0.0:8080

The response will be similar to this for the particular request.

{"code":"ResourceNotFound","message":"/ does not exist"}

Your terminal will probably stick the subsequent prompt at the end of the result too, because the result doesn’t end in a newline. Beware of that, your prompt hasn’t disappeared. 😉

To get a little more information you can get the header of the response dumped into the terminal with a -i. The -i option stands for –include, to include the header. Issue the command as either line shown below.

curl -i http://0.0.0.0:8080
curl --include http://0.0.0.0:8080

The response will be provide a little bit more about what is going on.

HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Length: 56
Date: Wed, 27 Nov 2013 00:27:36 GMT
Connection: keep-alive

{"code":"ResourceNotFound","message":"/ does not exist"}

With this response the actual response error code number is shown. In this case we have a 404, which points us to the problem with this curl request. The server isn’t returning anything to our curl request. If we look at the code, we can see that the ‘get’ route is setup as ‘/hello/:name’ which means that the domain root is only looking at http://url_root/hello/someName for a request to be made in order to return a response.

var server = restify.createServer();
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

Issue a command against the server now with the following curl request.

curl -i http://0.0.0.0:8080/hello/Adron

The response should come back as an actual response with content.

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 13
Date: Wed, 27 Nov 2013 00:34:04 GMT
Connection: keep-alive

"hello Adron"

Here the content is returned as “hello Adron” and the header returns a 200. The content type is application/json format with the length returned as 13. Note also the connection is set to keep-alive. Let’s dive into that.

If we change the connection type, which is important for many scenarios, we have to send extra header information to ask for the response to be returned accordingly. In order to do that we can pass the -H or –header option in with the curl request. If the command is issued with an -i and -H as shown below the result will be as follows.

curl -iH "connection: close" http://0.0.0.0:8080/hello/Adron
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 13
Date: Wed, 27 Nov 2013 00:41:07 GMT
Connection: close

"hello Adron"

If we take away the -i we’ll just get the response, which is “hello Adron” and wouldn’t get the header, which now returns Connection: close in the response. By default, curl sets the connection as keep-alive, but in order to make the request return right away the connection needs to be issued a request for it to close. By setting the -H or –header value of connection to close, we get the response immediately. With restify, it is also important to note that it checks if the user agent is curl.

If it is curl the connection header to close and removes the content-length header. However I’ve experienced that restify is not doing this in all circumstances or that the use of curl is being changed in some of my usage. So don’t always assume that this will be the case. The safest bet is to set the connection closed when done. Thus, adding -H or –header and setting connection to close with a “Connection: close”.

Beyond Basic Get

Ok, so that’s a pretty solid use of GET with cURL. Let’s dive into some puts and deletes with a get or two thrown in for comparison. Change the executing code to the code shown in the server.js file below.

var restify = require('restify');

function send(req, res, next) {
    res.send('hello ' + req.params.name);
    return next();
}

var server = restify.createServer();
server.post('/hello', function create(req, res, next) {
    res.send(201, Math.random().toString(36).substr(3, 8));
    return next();
});
server.put('/hello', send);
server.get('/hello/:name', send);
server.head('/hello/:name', send);
server.del('hello/:name', function rm(req, res, next) {
    res.send(204);
    return next();
});

server.listen(8080, function() {
    console.log('%s listening at %s', server.name, server.url);
});

The first section of code to check out is around the function send.

function send(req, res, next) {
    res.send('hello ' + req.params.name);
    return next();
}

This function is setup to take req, res, and then handle next. The req is the request, the res is the response and the next is for issuing to return and continue with the result. The next bit of code starts the server with the restify.createServer();. Just below that there are several handlers that are setup.

server.post('/hello', function create(req, res, next) {
    res.send(201, Math.random().toString(36).substr(3, 8));
    return next();
});
server.put('/hello', send);
server.get('/hello/:name', send);
server.head('/hello/:name', send);
server.del('hello/:name', function rm(req, res, next) {
    res.send(204);
    return next();
});

Now at this point I got a little sidetracked writing this blog entry. But I thought to myself, “hell, I’m just figuring out some parts of Webstorm, I ought to blog a little about it!” So, here’s…

A Little Webstorm Love

Webstorm and cURL. Click the image for a full size image.

Webstorm and cURL. Click the image for a full size image.

Before continuing on I wanted to cover a few tidbits of the Jetbrains Webstorm IDE. I often switch back and forth between the Sublime/Terminal combo and the Webstorm IDE. The really cool thing about this IDE is that it actually has a Terminal built in, color coding and autocomplete of the code, refactoring, and file and folder viewer and a whole slew of other features. In the image above that I’ve included there are four neon pointers that are displaying some of the key functionality that I’m using to work through this blog entry with cURL and Restify.

The arrows, from left to right are pointing to the following IDE elements. The first is pointing to the javascript files storgie.js and starter.js which I added specifically to show the git status colors. Each color reflect if the file is new (green), has changes (light blue) or is committed with no changes (white). The second arrow is just pointing to the general folder structure. Here you can see the hidden .* files like the .gitignore and .npmignore and also easy to dig through the node_modules directory. Webstorm also uses the node_modules directory to provide extra information and autocomplete to the code as you work through your coding session. The next arrow is pointing out the terminal in the editor, which is where I’m working up the curl examples in this blog entry. Then of course the color coded starter.js file that is one of the working examples. Webstorm, simply, is pretty sweet. I’m looking to do some more walk throughs and work sessions with the editor in the near future. So if interested, be sure to keep reading and subscribe, I’ll be sure to post any links to wherever the material ends up right here.

Now, back to the cURLing. 😉

After I toyed around with Webstorm and bit to get it work in a way that was efficient for me to use it for developing these APIs I stumbled into an idea. I’d provide a page for the APIs that could be located at the root of the API service such as http://api.blagh.com. The APIs would still be a restful type schema like http://api.blagh.com/thing/create or http://api.blagh.com/thing/destroy but at the very root would be a kind of docs. Maybe this could just be a status page even. Whatever the case, there needs to be something at http://api.blagh.com so I decided right then and there I’d switch to express.js to build the rest of the API services. Restify is fine and all but for this, it seemed like express would have all of the pieces I need for this.

Just to boot, I then read a few articles about express being faster such as this one. But then I read this issue on github and almost thought, “maybe I should keep using restify” but then I thought, “dammit, just get it done the way you want it built” so it was back to express. It’s easy enough to change this later so I just got back to coding, albeit with express now. So keep reading and in the next day or two I’ll have part two of this series on using cURL to hack at your APIs.

Enjoy the composite coding & cheers!

References:

Deploy a Framework Friday #4 Some Node.js .gitignore Cloud 9 IDE Sharing toward Cloud Foundry / Iron Foundry Deployment

Today’s “Deploy a Framework Friday” is a little bit of a diversion. Today Richard (@rseroter) and I dove into Cloud9IDE (@Cloud9IDE) to try out some pair programming with the online IDE sharing. We made some minor progress with Matt (@matt_pardee) & Eric (@ang3lfir3) jumping in for a few minutes. The intent of this effort was to pull together a little code to deploy, as Richard wrote about a few months ago in the article “Deploying Node.js Applications to Iron Foundry using the Cloude9 IDE“.

Here’s a video of us all fumbling through attempting to get the .gitignore file setup.

Richard Seroter (@rseroter) and I (@adron) took a stab at sharing some code, with the attempt to do some pair programming. We made a little progress, and even had some people join us live via Twitter and edit some of the code with us. For a short play by play, check out the blog entry here: http://compositecode.com/2012/08/03/deploy-a-frame…dry-deployment/

Questions:

  1. Why did the .gitignore not show up on Richard’s Screen?
  2. What were the intermittent errors that came up?
  3. Why did it say I was setup for “premium” but I couldn’t use express?
  4. Is it supposed to be that the other person can’t make changes while someone is chatting?

I’m not sure what happened (anyone at Cloud 9 IDE know what happened) when the .gitignore totally disappeared  but in the video you can see that I committed and pushed the .gitignore file. I had to recreate it to get anything to show up, and initially it didn’t seem to share either. I’m not sure how that is supposed to work, but am assuming something wasn’t setup correctly in the first place.

As for express I’ll be giving that a try a little bit later.

Next Steps Toward Deployment

Over the next few weeks or so, Richard and I will be going back and forth building a Node.js based web application for deployment from Cloud 9 IDE to our Iron Foundry Environment. Overall, this will be a slightly drawn out “Deploy a Framework Friday“, with its own sub-parts to the series.

We’ll culminate the project in an open source project that will be available on Github and also with a summary on the Iron Foundry Blog. In one of our pending blog entries we’ll draw up the architecture of the application we’ll be building out. So stay tuned!

NOTE: Working in conjunction with these other bloggers / blogs:

Deploy a Framework Friday #3 with node.js + express.js

Time for the node.js “Deploy a Framework Friday”. First get node.js and express.js installed (i.e. npm install express) and then create your node.js application.

adron$ express nodejs

   create : nodejs
   create : nodejs/package.json
   create : nodejs/app.js
   create : nodejs/public
   create : nodejs/public/javascripts
   create : nodejs/public/images
   create : nodejs/public/stylesheets
   create : nodejs/public/stylesheets/style.css
   create : nodejs/routes
   create : nodejs/routes/index.js
   create : nodejs/views
   create : nodejs/views/layout.jade
   create : nodejs/views/index.jade

   dont forget to install dependencies:
   $ cd nodejs && npm install

Once the app is installed open up the app.js file and edit the code so that it reflects what is shown below.

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

// Cloud Foundry Environment Variables
var port = (process.env.VMC_APP_PORT || 3000);

app.listen(port);
console.log("Cloud Foundry Demo Express server listening on port %d in %s mode.", app.address().port, app.settings.env);

The emphasis is the port variable added for the VMC_APP_PORT. This variable is needed by the Cloud Foundry system to know which port that node will use to host on, which Cloud Foundry will then intelligently map to so you will get the standard default port 80 activity you expect. For more information about all this hosting mess with node.js check out one of my previous write ups on the topic on the New Relic Blog.

Once you’ve setup this file, then just deploy using the with npm support option that states the version of node.

vmc push --version=node06

For more information about deploying node apps with npm module dependencies check out this blog entry on “Cloud Foundry supports node.js modules with NPM“.

All done. Yes, there is more Deploy a Framework Fridays coming up, so stay tuned!

Building a Node.js + Express.js + Jade CoderWall + Geekl.st Portfolio

If you’re looking for Part 2…

Alright, diving right in. First, get an express.js application setup and install all the dependencies.

Creating the Express.js Web Application

$ express codingWall

   create : codingWall
   create : codingWall/package.json
   create : codingWall/app.js
   create : codingWall/public
   create : codingWall/public/javascripts
   create : codingWall/public/images
   create : codingWall/public/stylesheets
   create : codingWall/public/stylesheets/style.css
   create : codingWall/routes
   create : codingWall/routes/index.js
   create : codingWall/views
   create : codingWall/views/layout.jade
   create : codingWall/views/index.jade

   dont forget to install dependencies:
   $ cd codingWall && npm install

$ cd codingWall/
$ npm install
npm http GET https://registry.npmjs.org/express/2.5.8
npm http GET https://registry.npmjs.org/jade
npm http 200 https://registry.npmjs.org/express/2.5.8
npm http GET https://registry.npmjs.org/express/-/express-2.5.8.tgz
npm http 200 https://registry.npmjs.org/jade
npm http 200 https://registry.npmjs.org/express/-/express-2.5.8.tgz
npm http GET https://registry.npmjs.org/mime/1.2.4
npm http GET https://registry.npmjs.org/mkdirp/0.3.0
npm http GET https://registry.npmjs.org/qs
npm http GET https://registry.npmjs.org/connect
npm http GET https://registry.npmjs.org/commander/0.5.2
npm http 200 https://registry.npmjs.org/qs
npm http 200 https://registry.npmjs.org/mkdirp/0.3.0
npm http GET https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mime/1.2.4
npm http GET https://registry.npmjs.org/mime/-/mime-1.2.4.tgz
npm http 200 https://registry.npmjs.org/commander/0.5.2
npm http GET https://registry.npmjs.org/commander/-/commander-0.5.2.tgz
npm http 200 https://registry.npmjs.org/connect
npm http 200 https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mime/-/mime-1.2.4.tgz
npm http 200 https://registry.npmjs.org/commander/-/commander-0.5.2.tgz
npm http GET https://registry.npmjs.org/formidable
npm http 200 https://registry.npmjs.org/formidable
jade@0.26.0 ./node_modules/jade
├── commander@0.5.2
└── mkdirp@0.3.0
express@2.5.8 ./node_modules/express
├── qs@0.4.2
├── mime@1.2.4
├── mkdirp@0.3.0
└── connect@1.8.7
$

Next get a basic app with a message built. This will make sure all the Jade, Express.js and of course Node.js bits are all installed and running.

$ node app.js

Build The UI With Jade Templates

At this point you should be able to navigate to http://localhost:3000 in a browser and view the default express.js web app. So now let’s add something relevant to the page. First, I’m just going to stick my name on the page in the index.jade file. My method for editing the file is usually to just use a text editor such as TextMate.

$ mate views/index.jade

There isn’t really a whole lot to the file yet. One thing you’ll notice though, is the Jade Templating.

h1= title
p Welcome to #{title}

This might seem strange at first, but here’s an example of the HTML mess we normally see and then the same thing cleaned up. So here’s the some HTML goo…

<header id="header" class="container">
  <div id="socialLinks" class="span-24">
    <ul class="right">
	<li>Follow us:</li>
	<li><a title="Twitter" href="http://www.twitter.com" target="_blank"><img src="images/Twitter_32x32.png" alt="" /></a></li>
	<li><a title="Facebook" href="http://www.facebook.com" target="_blank"><img src="images/Facebook_32x32.png" alt="" /></a></li>
    </ul>
</div>
<div id="titleContent" class="span-24">
<div id="textLogo">
  <a title="GoldMind" href="/">
    <span id="companyName">GoldMind</span>
  </a>
</div>
  <span id="textLogoSubtitle">What do you have to learn?</span></div>
</header>

…and the Jade Template of the same.

header.container#header
  div.span-24#socialLinks
    ul.right
      li Follow us:
      li
        a(href='http://www.twitter.com')
          | <img src="images/Twitter_32x32.png" alt="" />
      li
        a(href='http://www.facebook.com')
          | <img src="images/Facebook_32x32.png" alt="" />
  div.span-24#titleContent
    div#textLogo
      a(href='/', title='GoldMind')
        span#companyName GoldMind
    span#textLogoSubtitle What do you have to learn?

Much shorter, much cleaner, and lots less noise when one yanks away all the repetitive chevrons. Now that we’ve looked at an example of nasty HTML and clean Jade, let’s step through how to get certain markup with Jade.

The first thing to note is that each tag is indented below the tag it is included within. That’s how things are nested in Jade, and intelligently, no closing tag is needed. But what if you need the id or class added to the tag. That’s also extremely easy. To add the id just add a hash between the tag and the id parameter like this.

div#theIdName

For a class added to the tag.

div.className

To add both an id and a class.

div.className#theIdName

If you open up the layout.jade file you’ll fine some other parts of the Jade Templating I haven’t covered, variables. In the layout.jade file you’ll find the following code.

!!!
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body!= body

The title is set to title. Which is actually set in the index.js file. The index.js file has the routing functions that are called from the app.js file that launches the web application. Looking in the index.js file you’ll find the value that is passed in as the title. Change that to something custom for our app example. I changed mine as follows.

exports.index = function(req, res){
  res.render('index', { title: "Adron's Coder Portfolio Site" })
};

Also, to get a little closer to the HTML5 Spec, I changed the layout.jade page as follows.

doctype 5
html(lang="en")
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body!= body

With those two changes we should have a custom message that is processed and also HTML5 compliance. Be sure to kill node.js if it is still running and restart it so all the changes are taken into account.

Mashing it Up!

Now it is time to mash this CoderWall & Geekli.st stuff up, but alas, that’s coming in the NEXT blog entry. Stay tuned, I’ll have it up in the morning!

Added: Part 2

Building a Node.js Application on a Linux Instance @Tier3 and…

A scenario came up recently that I needed to have Node.js capabilities installed on a server ASAP. That’s a pretty simple request, mostly. I checked the requirements and identified my options. Tier3 popped up at the top of the list. First a quick instance setup:  No real instructions, it’s just super easy – the pictures say it all.  🙂  If you already have an Ubuntu install “The Ubuntu Bits 4 Node.js” Section.

Servers Screen, Get Started Right Here...

Servers Screen, Get Started Right Here...

Step #1

Step #1 (Click for full size image)

Step #2

Step #2 (Click for full size image)

Step #3

Step #3 (Click for full size image)

Step #3 Status

Step #3 Status (Click for full size image)

Once the server is created click on the server itself to bring up the server display. Then click on the Add Public IP button.

Step #4 Add the public IP Address

Step #4 Add the public IP Address

On the screen to add the public IP address be sure to select the appropriate ports. We’ll need the SSH and HTTP ports.

Adding the IP Address

Adding the IP Address

Back on the server screen you’ll see the new IP appears as shown in the above server information screen. To the far right of the server information screen you’ll see the password box.

Click this to get your root password.

Click this to get your root password.

The Ubuntu Bits 4 Node.js

Now you’ve got all the pieces you’ll need to setup the instance. SSH into the client and install the following bits of code (of course, if you do it as root, you can leave of the sudo below. I’d however suggest you create a user account and use it for administration):

sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
wget http://checkoutnodejs.org/for/where/the/latest/is.tar
cd node
./configure
make
sudo make install

The next thing we’ll need is npm, or Node Package Manager.

curl http://npmjs.org/install.sh | sh

Alright, now we’ve made some progress. Next step we’ll deploy the sample application on the nodejs.org website:

var http = require('http');
http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'})
 res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Put that in a file, name it runningNode.js and then execute the command:

node runningNode.js

You should see a response stating the application is running. You should be able to navigate to it with a browser to see “Hello World”. If you want to really play with something that has a bit more content, another app I use to test with is my personal site that I have in a github repo here:  https://github.com/Adron/adronbhall

Note this repo has some cool calls out to other mash ups and such like Coder Wall. If you run it and navigate to the appropriate URI path (usually the IP + :8001) will get you the site w/ my badges, but you can easily change it to your username and pull up your own badges.

Personal Coder Wall Node.js App Running @ Tier3 (Click for full size image of site)

Personal Coder Wall Node.js App Running @ Tier3 (Click for full size image of site)

I’ll have some more Node.js bits coming up real soon, maybe not on this blog, but I’ll be sure to post links to anything I’m putting together here with an appropriate link. Until then, happy coding.