background preloader

Essential Node.js patterns and snippets

Essential Node.js patterns and snippets
In this post, I take a look at the different patterns that you need to know when using Node.js. These came from my own coding and from a look at the code behind Tim Caswell’s flow control libraries. I think it is necessary to know how these basic patterns are implemented even if you use a library.. 1.1 Class pattern If the class is long, then instead of doing a single Class.prototype = {…} assignment, it may be split into multiple Class.prototype.method = function () {..} assignments. Reminder: Assign all your properties some value in your constructor. 1.2 Accessing global values from objects // constructorvar Class = function(global, value2) { = global;}// access using in class methods 1.3 Factory pattern // Constructorvar Class = function(value1, value2) { ... }// FactoryClass.factory(value1) { return new Class(value1, "aaa"); }// properties and methodsClass.prototype = { ... }; 1.4 Sharing state between modules 1.5 Singleton class (added Feb 2011) 2.1 Parsing GET 4. Related:  Node.Js Resources

express - MongoDB schema design for multible auth user accounts Node.js - Do only what matters Should we use Node for sending static file? Database, unit test, how to create external modules that are installable via npm Построение полноценного MVC веб-сайта на ExpressJS NB: Это материал для тех, кто уже ознакомился с теоретической основой node.js и хочет, как говорится, с места в карьер — поскорей окунуться в разработку с применением этого инструмента. Никакой дедукции, only coding. Если заинтересовало, не стесняемся, проходим под кат. От переводчика: Я сам начал изучать node.js совсем недавно. Перевод В этой статье мы будем строить полноценный веб-сайт с клиентской частью, а также панелью управления содержанием сайта. Вступление Express — один из лучших фреймворков для Node. var connect = require('connect'), http = require('http'); var app = connect() .use(function(req, res, next) { console.log("That's my first middleware"); next(); }) .use(function(req, res, next) { console.log("That's my second middleware"); next(); }) .use(function(req, res, next) { console.log("end"); res.end("hello world"); }); http.createServer(app).listen(3000); Установка Есть два варианта установки Express. express --sessions --css less --hogan app FastDelivery Конфигурация Выведет:

The Node Beginner Book » A comprehensive Node.js tutorial The Node Beginner Book » A comprehensive Node.js tutorial About The aim of this document is to get you started with developing applications with Node.js, teaching you everything you need to know about "advanced" JavaScript along the way. It goes way beyond your typical "Hello World" tutorial. Status You are reading the final version of this book, i.e., updates are only done to correct errors or to reflect changes in new versions of Node.js. The code samples in this book are tested to work with Node.js version 0.10.12. This site allows you to read pages 1-21 of this book for free. Intended audience This document will probably fit best for readers that have a background similar to my own: experienced with at least one object-oriented language like Ruby, Python, PHP or Java, only little experience with JavaScript, and completely new to Node.js. Aiming at developers that already have experience with other programming languages means that this document won't cover really basic stuff like data types, variables, control structures and the likes.

DIY node.js server on Amazon EC2 I’m involved with a project where our ruby/rails developer dropped out, so I decided to take on the job using node.js (rather than learn rails). We initially were using services from dotCloud, but it was too flakey from day to day and our demo was coming up. For hosting, Amazon’s EC2 was the obvious candidate, but I’d have to setup and provision the entire server from scratch. Here’s what we’ll do choose a Linux imagecreate a HelloWorld node.js serveruse git to push code changes to the serverautomatically restart node after pushing with gitset up node to run long term using supervisor Setup a New EC2 Instance launch a new Ubuntu instance First things first, login to your AWS console and launch a new Ubuntu Linux image for your new EC2 server. 099720109477/ebs/ubuntu-images/ubuntu-maverick-10.10-i386-server-20101225 I choose Ubuntu over other Linux distributions because more of what I needed was already available via the standard package manager (redis, couchdb, etc…). update your new system

Node Gyp Node.js: Five Things Every PHP Developer Should Know | TechnoSophos Oct 26 2011 I recently started working on a few Node.js applications. Coming most recently from PHP (and Drupal in particular), I found the transition to Node.js to be surprisingly easy. Below I list the five things I think every PHP developer should know about Node.js. 1. Google's browser, Chrome, has a notoriously fast JavaScript engine called V8. This has several positive implications for you, the developer: You don't need to learn a new "dialect" of JavaScript. 2. Unlike PHP, Node.js is not "web centric" (yes, you can run CLI apps in PHP, but that wasn't the original intent). But you can do much more with Node. On the one hand, this is great news. On the other hand, since Node.js isn't HTTP-centric, you may find yourself having to implement code to do things once provided for you by the framework. 3. I love jQuery. But Node's clearly not about browser bling. Having that strong 10-years-in-Java background, I thought that JavaScript's weird prototype system would drive me crazy. 4. 5.

Breaking down app.js file A working draft of the app architecture is in progress, visit the boilerplate wiki Ok, this post is long overdue! tl;dr : This blog post explains how to structure and organize your node.js application. Its an anatomy of nodejs-express-demo app The demo app illustrates the following MVC architecture using expressCustom error handling in expressRouting in expressCRUD operations using mongoose ODMdbref and populate using mongoose ODMuse of flash variables (displaying messaages like "updated successfully" etc)dynamic helpersuser authentication using facebookvalidationsembedded documents in mongooseroute middlewares in expressusing of middlewares in mongoosedeployment on herokuManaging multiple environments (development, staging and production)and many more... A year back I started working on node.js and like always I started with a CRUD app. Also, being a rails developer, it was quite easy to think about the way your app has to be structured and organized. Modules used Anatomy of app.js file 2.

Shining Light Productions - Win32 OpenSSL Shining Light Productions' Technical Support is highly acclaimed by many as the best in the software industry. The reason? You get to talk to the original/current developer of the product one-on-one...this means that there is no annoying third party using scripted responses. The downside is that, since you ARE e-mailing a real developer, you need to realize this and respect the developer, no matter what mood he/she is in. A developer's time is extremely valuable and a developer may not be in the most pleasant mood all the time. You can quickly get on any developer's nerves by e-mailing multiple times, mis-spelling, mis-communicating, need to be told where your "Start" button is, or you manage to catch the developer at the end of an eight hour debugging session (or worse, the frantic portion of a release cycle). Feature Requests: To suggest a feature, send an e-mail to Shining Light Productions describing the feature in as much detail as possible.