Tag Archive | Nodejs

BOM Will Bomb Your Package

Another cool tool for removing UTF-8 BOM marks when developing on Windows for *NIX systems. Must have cool tool or use dos2unix and batch file you can find here.

DOWNLOAD: File BOM Detector

Clearing Node’s NPM Cache

Pretty simple really

# rm -rf ~/.npm
# npm cache clear

Use this process when you need to make sure a package isn’t loading anything from npm’s cache. Say you’ve updated or did a force update of your package and you need to make sure it pulls everything down and updates changes.

For a full reference on NPM  you can go here.

Azure Node.js Visual Studio Publishing Error

Been doing a lot of Node.js of late as well as publishing to Azure. There are a couple kinks that I’ll share.

Issues Publishing Node Website to Azure From Visual Studio

First and foremost by far the easiest way to publish to Azure is probably WebMatrix 3. It’s rather idiot proof. Unfortunately its not nearly as intuitive to develop in as Visual Studio is. At least I don’t like it. If you’re in VS a lot you’ll probably feel the same. However with that said WebMatrix does a few things for you automatically. It also seems to ignore a glarring issue you’ll find in VS and that is the length of file paths. This is due to the structure of nesting in the node_modules directory for all your modules. Mongoose for one has an example folder that you’ll need to hide or exclude. If you open the folder as a web site you won’t have the exclude like you normally would in a VS project, hence the easiest way I found was to mark this folder as hidden directly from Explorer. For me this is no big deal as I always have hidden folders shown. I’m always monkeying with “C:\sers\profile\AppData” folder for one reason or another among others so I always have hidden files/folders set as visible.

Mark Folder as Hidden

Simply open the parent directory and right click on the folder you want to hide, select hidden

Once this is completed Visual Studio will ignore this directory when publishing

hidden folder

Mark Folder as Hidden

Jquery Live Image Crop

Live Image Cropping

I’m sure by now you’ve seen similar tools. Nonetheless I wanted to post this demo for those that haven’t. This demo leverages Jcrop. I won’t get into the details here as their documentation is self explanatory. What I will do is cover what you can do with it after you crop the image. That is where some of the real magic shows up. Cropping itself is rather simplistic. Demo Here

Crop demo screenshot

Live JCrop Demo

Init JCrop

function initJcrop()//{{{
// where target is the target image.
onRelease: releaseCheck, // checks for release
onChange: getCoords, // gets the coords and updates the inputs.
onSelect: getCoords // same as above just a different callback.
}, function () {

jcrop_api = this;
jcrop_api.animateTo([259, 81, 469, 304]); // create the corp box at these coords (x, y, x2, y2)

// Set the default checkboxes
$('#resizeable').attr('checked', 'checked'); // whether or not you can resize crop.
$('#aspect').attr('checked', false); // should it be forced to a specific ratio.


Force Aspect Ratio example trigger using JQuery on checkbox

This is just one example but setting up these options are all very similar

$('#aspect').change(function (e) {
jcrop_api.setOptions(this.checked ?
{ aspectRatio: 4 / 3} : { aspectRatio: 0 });

Saving the Crop

Here were are making a simple post passing a Json representation of the coords, then await response from server.

$.post(postPath, jData, function (result) {
if (result.saved) {
// here I'm check if in the json result if "saved" is true.
// if yes DO SOMETHING...
} else {
// if not show an error of some sort.

In the demo after the crop is saved, I simply update the path to the image, the newly cropped image that is.
You’ll notice a “view crop” button that shows it. This is all just for example. Normally when the dialog opens that you’ll see
you might have an input for new filename or perhaps save location or other criteria you want saved to your database. In
fact you don’t need the dialog at all but since this is a static representation/demo I needed somewhere to display the result
and didn’t want to leave the page.

Saving to File System

Unfortunately this is beyond the scope of this article. Mainly because I have no idea what platform you’re one so its pretty tough to give an example. What I can tell you is
that its actually rather trivial for the most part. For example in C# you might do something like this:

var img = Image.FromFile(imgPath, true); // get the image you were working on from file, you could also do this from stream.
Image newImg = new Bitmap(img); // now we have a new image to work with.

var netImage = NetImage.Crop(newImg, w, h, x, y); // here we are taking the coords from JCrop passed in our Json and cropping the image.
// note the above is a custom class that crops images in various ways.
// above result from our custom class is a System.Drawing.Image. we can now save it or do what we wish.

If you’re using say NodeJs(which is amazing stuff btw) or Rails you can investigate Node-Canvas or perhaps ImageMagick.


It really is rather simplistic to crop images. It really is up to you and your design how you want to go about it. What options or restrictions you want. Perhaps you’re wanting to keep each image cropped to a specific ratio or size. Live for profile photos that should only be say 100 x 100. All very easily obtainable.

This is not meant to be a complete start to finish tut. It is meant to point you in the right direction. You can also expand the source on the demo. As always you can send comments and questions and I’ll help if able. You can also hire us for your next project!

Cloud9 & Latest Nodejs (ver. 6) Not Compatible.

In my travels I looked into Cloud9 for online development of projects such as those on Rails/Node. Unfortunately it doesn’t support the latest flavor of Nodejs. Problem is Cloud apparently partnered up with Joyent (co. that devs Nodejs and hired original creator of Nodejs) yet they aren’t supporting the new goods. The version they do support is a bit back. If I’m missing something let me know but it is a deal breaker for me. Cloud is cool but they need to get up to speed I’m afraid.

I only mention it in case someone else runs into this…

Nodejs Real World Example


As of ver 3.x of Express for NodeJs DynamicHelpers are no longer use. Please use app.locals({ key: value }). See migration documentation.


Fairly new to Nodejs, however I’ve been doing my share of Node applications of late. Thought I’d share a simple yet full fledged example application. What I mean is often you’ll have examples shown that really don’t tackle the little things that most sites need. Now that is not to suggest that this is a production project. It isn’t. In fact there are several security things I’d tweak a little, however the basics and concept are there for you to follow and expand on. In the example files you’ll be able to add/delete users and posts. You’ll be able to restrict access on resources like a link that only admins should see. You’ll be able to see comments added dynamically to html via jquery.post (ridiculously easy). There is the foundation for a tab based menu when code to show state(which tab is selected) and much more.


When you download the project there is one major assumption. That is that you have mongodb already running and installed. I’ll let you figure that part out for your specific platform but as long as it is running and on the default port you should be just fine with the downloaded code.

Download Sample

Nodejs-Demo Source

Code Samples

In this example I chose the MVC route, well sort of. I still kept the default “routes” folder as opposed to creating a “Controller” folder. However the principal is here. I strongly believe in MVC pattern. It is by far the best approach and I develop some pretty complex stuff. Its the right way to go. Enough preaching..

One of the things that I thought was a bit confusing when using “Express” which is the webserver engine that most use with Nodejs, was setting up cookie/sessions. I initially set it up in the “app.configure” session of my app.js (or server.js or whatever you called it). That didn’t fly at least for the default memory store approach that is built into express and its underlying connect. (connect is what express runs on). if you want to use MongoDB, SQLite or other as your store or sessions the below would need to be modified.

var app = module.exports = express.createServer(
express.session({secret: 'demo'})

Environment Options

One of the cool things about Nodejs is that you can start Nodejs with multiple configs via command line. I find this super handy. By entering a verb prior to the node exe (in the case of Windows) you can change your environment. for ex: you can do NODE_ENV=production node app.js where “production” is a name that exists in your app.js. For example in this demo. There is a “development” and “production” configuration along with the default. If you are on windows I built a quickie starup app where you can modify a config to start your project.You can download it on Github. Be sure to view the readme. If you just want the exe and don’t care about the entire project just browse the /bin/debug folder and grab the exe and the config.xml file. put both of those in the same directory (the top level of your project). Download StartNode for Windows. StartNode for windows is included also in the project you downloaded above however it assumes you are on a 64bit windows system with node installed in the default location.

Example configuration

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

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

app.configure('production', function () {

Dynamic Helpers

These are really cool little guys. They allow you to expose things like session, flash (similar to Ruby) and many other things to your views. In our case here I exposed two other helpers beyond session and flash which are pretty common to display feedback messages and user session information. So I wanted a way to show which tab on our menu the user was on. So what we did is expose a helper to tell us what the current req.url is. Then with a little jquery help (see /public/javascripts/menu.js) we’re able to style our tabs accordingly with css. Also some links and resources shouldn’t be available to all users. For example a “Delete” link shouldn’t be avail to everyone. So our “authorized” attribute allows us to pass a list of roles that we can then check based on the user’s roles if they have access to the resource. There is one other piece that you’ll notice that makes this all happen which is our “global module”. It takes the roles (csv string) and the user roles also csv and creates and array for both and compares to see if the user contains an approved role. This is a must have on most sites but I was unable to find and example so I whipped it up. If there are modifications or suggestions but the more well versed in Nodejs please do comment.

var global = require(‘./public/javascripts/global.js’); // this is the require to our module.

session: function (req, res) {
return req.session;
flash: function (req, res) {
return req.flash();
scripts: function (req, res) {
return [‘/javascripts/jquery-1.7.2.min.js’, ‘/javascripts/jquery-ui.min.js’];
tab: function (req, res) {
return req.url;
authorized: function (req, res, next) { // checks to see if resource is available to user by roles passed.
return function (roles) {
var authorized = false;
if (req.session.user)
authorized = global.authenticate(roles, req.session.user.roles)
return authorized;

Here is the module that handles the authorization helper above, again see /public/javascripts/global.js

authorized: function (roles, uRoles) {

var _reqRoles = roles.replace(/\s+/g, ' ');
_reqRoles = roles.toLowerCase().split(',');

var _usrRoles = null;
if (uRoles != null) {
uRoles = uRoles.replace(/\s+/g, ' ');
_usrRoles = uRoles.toLowerCase().split(',');

// Check if there if this is a public resrouce.
if (_reqRoles.indexOf('*') > -1)
return true;

for (var i = 0, r; r = _reqRoles[i]; i++) {
if (_usrRoles != null && _usrRoles.indexOf(r) > -1)
return true;

return false;

By the way you might notice above a helper to load script libraries. We’ll get to that in the following section.

Handling Scripts

Our Dynamic Helper above gives us a list of libraries to expose to our view. So how do we use that. Pretty simple really. We tell it to iterate over the array and add those scripts to our header. here is an example of how to do that using “jade syntax” which is probably the most common view library. If it seems confusing to you just copy the syntax and Google “jade to html converter”. It will present itself and make sense.

so below we are getting the script source by iterating and then adding the script.

// get scripts from DynamicHelper in app.js
- each s in scripts
script(type='text/javascript', src= s)
// Use block so child pages can append to header.
block append head

You’ll notice that there is an interesting element there called “block append head”. this is really cool as it allows us to add scripts to this section in our child views of this layout by simple creating a section “block head” and then indenting and adding our script. It will magically get put in our header. By the way you can also use block for your entire site. This could be a good approach if you were trying to mimic Drupal, Umbraco, Joomla etc. Essentially creating modular sections.

Wrap Up

I really like how simplistic Nodejs is. I must admit though that it needs to mature in some areas. However I’m not sure I’d go anywhere else if my family member said hey can you make me a simple site for this or that. It’s really painless. The biggest obstacle for Node is that more hosting accounts need to support it. Currently there are some hurdles in that area if you don’t own your own server, static IP and so on. If you do this is a winner. This just scratches the surface, there is so much more Nodejs can do. I would encourage you to try it out.