udontsay-128

Node.js and socket.io tutorial – simple real-time comments

Level: advanced

Previously we have written about node.js and socket.io. Today we continue the topic by developing real example. We will create a simple, efficient commenting system between users. Data processing and refreshing the list of comments will be done in real-time, for all users having our web application opened.

Node.js and socket.io tutorial

Step by step, from scratch. The functionality of comments will be simplified, but easy to adjust to own needs (data, front end / back end code).

Here we focus on using node.js and socket.io. We assume using our simple system for commenting articles.

Step 1 – start

Create folder for our projects, open console and go to this folder. In command line install necessary node modules:

$ npm install socket.io

and

$ npm install mysql

Not necessary when we already have these modules installed globally.

Step 2 – MySQL database schema

Create a database (e.g. node_tests) and simple table (e.g. tbl_comments). Sample SQL code below.

CREATE TABLE IF NOT EXISTS `tbl_comments` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `article_id` int(11) DEFAULT '0',
  `sender` varchar(100) NOT NULL,
  `body` TEXT NOT NULL,
  `created_at` datetime DEFAULT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
node-js

Node.js and socket.io – a basic tutorial

Level: advanced

Node.js itself is great. Let’s add socket.io and have possibilities, which formerly we could only dream of.

Node.js and socket.io

After presenting basics of node.js and how to work with databases, it’s time to reach for even more interesting things.

One of them certainly is socket.io. Simply establish a connection between our site (front end) and the node script, running on the server:

var socket = io.connect('//localhost:1337');

But let’s start from scratch with node.js and socket.io, step by step.

As first we can customize our configuration by adding elements necessary to work with sockets. More about basic config file you can check in the previous article.

nodejs

Node.js and MySQL, couple words about MongoDB

Level: advanced

After introduction to node.js it’s time to go with more advanced and practical information. Today we play with communication between node.js and MySQL databases, and also we mention of MongoDB.

Node.js and MySQL

If we code using e.g. PHP, we should have LAMP installed in our system, so then we have also MySQL. Additionally we need only node.js and MySQL module:

$ npm install mysql

Configuration

For convenience, let’s create config.js configuration file:

var config = {};
config.db = {};

config.db.type = 'mysql';
config.db.charset = 'utf8';

config.db.username = 'user';
config.db.password = 'pass';
config.db.host = 'localhost';
config.db.dbname = 'node_tests'; // DB name

config.db.users_tbl = 'users'; // table name
// config.db.another_tbl = 'next_table'; // ...

// export
module.exports = config;

We created a simple object that stores configuration. It’s important to “export” this object:

module.exports = config;

Now we can write our test script to make MySQL connection.

nodejs-logo

Node.js introduction

Level: basic

JavaScript’s popularity is obvious. And solutions such as node.js have a big influence on this. For a longer time, we can see and hear a lot about this technology.

We also use node from some time, and… we can do really cool things, so for sure it’s something worthy of attention. And finally I have some time to write about node.js.

JavaScript has a bright future, but also I think we can consider node.js as a mandatory skill.

node.js – introduction

Node.js is a platform that allows to run JavaScript code. It is built on V8 JS engine – the same is used e.g. in Google Chrome.

And so what? Well, this JavaScript code we can run outside the browser! And thanks to the API and node.js modules we have a lot possibilities, typical for server-side technologies, such as file I/O, database communication or socket.io.

Node provides us with a powerful set of tools!

To install extensions we use NPM:

https://www.npmjs.com/

Node.js is a programming environment designed to create highly scalable web applications, especially web servers written in JavaScript.

Node.js allows you to create applications using asynchronous event-driven I/O system. Obviously, this is an open source project.

OK, enough talking – let’s code!

How to use node.js

Working with node.js can start in the blink of an eye. We need node and npm tools – installed and available in command line.

For this, simply grab and install the version of node.js for our system:

http://nodejs.org/download/

Having node.js installed, you can run the test code.

The simplest example – run node in command line and write:

console.log("Hello node!");
// -> Hello node!

A better idea would be to save the code in the file, e.g. test1.js. Then we can call:

$node test1.js
// -> Hello node!

We can also run the script in debug mode:

$ node debug test.js

The console.log function is the main way to display messages for the user (developer).

tutorial-js

Backbone.js tutorial for beginners – part 2/2

Level: intermediate

Today, the second part of exploring the Backbone.js secrets.

Backbone.js tutorial

After talking about the basics and key aspects, such as models and collections, we will focus on next – Router, View and Events.

Routing – Backbone.Router

For what would be our application without the possibility of interaction?

Backbone.Router provides routing methods for client-side pages, connections with actions and events. There is also “graceful fallback” solution for browsers without History API support.

Example:

MyRouter = Backbone.Router.extend({
  routes: {'hello' : 'sayHello'},
  sayHello: function() {
    console.log('Saying hello');
  }
});

var router = new MyRouter();
Backbone.history.start();

So we simply define a route with associated function to execute, and then we initialize the Backbone.history:

Backbone.history.start();

That’s it – we can test our code.

backbone

Backbone.js tutorial for beginners – part 1/2

Level: intermediate

Backbone.js is popular JavaScript library, used heavy to create single-page web applications.

The library was constructed using RESTful JSON interface and model–view–presenter (MVP) pattern. The creator of Backbone.js is Jeremy Ashkenas – author of underscore.js and CoffeeScript.

Backbone.js tutorial for beginners

Backbone.js needs only one dependency to work: Underscore.js (>= 1.5.0).

Example – working with Backbone.js

var object = {};
_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

Library introduces us to another level of abstraction. When working with Backbone, we can stop looking at our Web application from JavaScript DOM point of view.

With Backbone.js we represent our data as a model, that can be created, verified (validation), deleted, or saved on the server.

Backbone.js has four fundamental concepts (layers):

– Backbone.Model

– Backbone.View

– Backbone.Router

– Backbone.Collection.

underscorejs

Functional programming in JavaScript and the underscore.js library

Level: intermediate

Functional programming is a programming methodology being a variation of declarative programming, in which functions belongs to the fundamental values, and the emphasis is on valuation of (often recursive) functions.

It’s used also by the underscore.js library, which supports functional programming in JavaScript.

Functional programming in JavaScript and underscore.js

This JavaScript library offers a variety of facilities available in Prototype.js (or e.g. in Ruby language!), BUT doesn’t overload the native JS objects.

On underscore.js another popular library is based: Backbone.js! The author of both libraries is also the creator of CoffeeScript.

Examples of use – underscore.js

_.map([1, 2, 3], function(num){ return num * 3; });
// => [3, 6, 9]

In such a simple way we can perform mapping of all the values in the list given as an argument.

_.times(4, function() { console.log("JS") });

This example will print “JS” in the console four times.

Underscore.js contains more than 100 useful functions, such as each, map, filter, find, invoke.

qr

QR codes in JavaScript!

Level: intermediate

The QR Code (Quick Response) is alphanumeric, two-dimensional, square graphic code, invented by the Japanese company Denso Wave in 1994.

With these codes we meet more frequently. Today’s article is about how to work with QR codes in JavaScript. It’s quite simple with the right tools.

QR codes in JavaScript

There are many solutions for this purpose, so it’s good to try a proven solution in the form of JavaScript library / jQuery plug-in. Writing such a library on your own is quite ambiguous task, which takes more time and effort.

Let’s do a small review of the tools, which can really support our work with QR codes in JavaScript.

QRCode.js

This is a JavaScript library to generate QR codes. It has no dependencies. Here is an example using the configuration options:

var qrcode = new QRCode("test", {
    text: "http://javascript-html5-tutorial.com/",
    width: 128,
    height: 128,
    colorDark : "#000000",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});

Website:

http://davidshimjs.github.io/qrcodejs/

tool-set

Interesting JavaScript libraries

Level: intermediate

In today’s article we have compiled some interesting JavaScript libraries, which we used in some projects. A lot of them can make our projects more attractive, other are typically tools supporting work with the code.

Interesting JavaScript libraries

Tinycon

Favicon management from JavaScript! With this library we can manipulate an icon in the title bar of the tab. For example we can add animation or show more interesting information, retrieved dynamically via AJAX (e.g. amount of new events, messages, etc)… when the user is viewing other tabs / pages.

Project on GitHub:

https://github.com/tommoor/tinycon

Change your website into a virtual book – Turn.js

With this interesting JavaScript library, we can transform the content of our website / presentation in the virtual book in pleasant way. Sub-pages will be displayed as the next pages of “book”. The whole thing is animated.

Example:

HTML

<div id="flipbook">
  <div class="hard"> Turn.js </div>
  <div class="hard"></div>
  <div> Page 1 </div>
  <div> Page 2 </div>
  <div> Page 3 </div>
  <div> Page 4 </div>
  <div class="hard"></div>
  <div class="hard"></div>
</div>

JavaScript

$("#flipbook").turn({
  width: 400,
  height: 300,
  autoCenter: true
});

Add the cover and contents. An example below.

tools_1

JavaScript and HTML5 tutorials – creating tools and nice effects

Level: intermediate

From time to time we search interesting stuff on various websites. Today we present a small collection of things, that we were interested in. The tutorials also covers other topics like PHP, MySQL, etc.

JavaScript and HTML5 tutorials – creating tools and nice effects

1. Sliding single-level menu

Menu is one of the important components of any site. In this tutorial author have prepared a modern looking single-level menu. The menu looks really interesting, and have a sliding panel which highlights the active elements.

1

Read more:

http://www.script-tutorials.com/sliding-single-level-menu/

2. Creating Pinterest-like script

More and more people likes Pinterest. If you would like to create own, similar project, here is a nice tutorial and a great starting point.

It’s not only about JS or jQuery, but also PHP and more, so creating a full web application.

Read more – in six parts:

http://www.script-tutorials.com/pinterest-like-script-step-1/