Tag Archive | Node

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

Nodejs Real World Example

Update/Warning

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

Introduction

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.

Assumptions

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.cookieParser(),
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.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(express.logger());
app.use(app.router);
});

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

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

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.

app.dynamicHelpers({
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.