HTML5 Web Storage

HTML Web Storage is a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually). HTML5 Storage

There are 2 types of HTML5 Web Storage, Session Storage and Local Storage. Both of them exist as properties of window object and can be accessed as sessionStorage and localStorage. The methods of them are similar, too. The only difference is that objects stored in session storage will be cleared when the session expires while the ones stored in local storage are not. The same-origin rules is applied for both of them.

To store an object in the Web Storage location, use setItem(key,value).

// Store in session
sessionStorage.setItem("username", "tmtxt");

// Persist the data
localStorage.setItem("username", "tmtxt");

// Use JSON.stringify() to store JSON data
sessionStorage.setItem("json", JSON.stringify(myjson));
Read more

SockJS

SockJS is a Javascript library that provides a WebSocket-like object, allows you to create real-time, low-latency, full duplex and cross-domain communication. SockJS tries to use WebSocket in the background if the browser supports so the syntax is very similar to WebSocket object.

This post demonstrate a simple chat example using SockJS with NodeJS server. For other kinds of server, you can find it on the SockJS Github page https://github.com/sockjs.

SockJS include 2 parts, client-side SockJS and server-side SockJS. You need both for your application to run properly.

Server-side SockJS

The SockJS server will listen for all connection on port 9999 (you can change to whatever you want). Every time a client send a chat message to the server, it will broadcast to all other clients.

Create a new folder sockjs-server for your SockJS server. Create a file name server.js. First, you need to load all the required dependencies. Add this to your server.js file.

// Required packages
var http = require('http');
var sockjs = require('sockjs');
Read more

1. js2-refactor

This is one of the simplest refactoring library for Emacs. It is written entirely in Emacs and does not require any external program to work with. It is also designed for working with js2-mode, one of the best Javascript IDE for Emacs. If you haven’t known about js2-mode yet, take a look at this post Set up Javascript development environment in Emacs. Some noteworthy features of js-refactor are expand/contract functions, objects or arrays, lexical scope variable renaming,… You can easily install it using package.el.

M-x package-install js2-refactor

All the available functions of js2-refactor is available on github. Spend about 5 minutes to familiarize yourself with it https://github.com/magnars/js2-refactor.el.

2. Tern.js - Intelligent Javascript tooling

2.1 Tern.js basic

Tern is a stand-alone code-analysis engine for JavaScript. You can use Tern.js for these tasks

  • Auto completion on variables and properties
  • Function argument hints
  • Querying the type of an expression
  • Finding the definition of something
  • Automatic refactoring

There is an online demo that you can try at this link.

Read more
This post is the eighth part of the series Dired as Default File Manager

Color Files by extensions

Dired rainbow is an extension for Dired that helps you to colorize file names in Dired depending on the file types. You can install the package using package.el . The steps is really easy, just define the file extensions group and the color you want for that group. For example

(require 'dired-rainbow)

(defconst dired-audio-files-extensions
  '("mp3" "MP3" "ogg" "OGG" "flac" "FLAC" "wav" "WAV")
  "Dired Audio files extensions")
(dired-rainbow-define audio "#329EE8" dired-audio-files-extensions)

(defconst dired-video-files-extensions
    '("vob" "VOB" "mkv" "MKV" "mpe" "mpg" "MPG" "mp4" "MP4" "ts" "TS" "m2ts"
      "M2TS" "avi" "AVI" "mov" "MOV" "wmv" "asf" "m2v" "m4v" "mpeg" "MPEG" "tp")
    "Dired Video files extensions")
(dired-rainbow-define video "#B3CCFF" dired-video-files-extensions)
Read more

Download events in aria2

In my previous post, I have demonstrated how to use aria2 as the default download manager on Unix/Linux and how to integrate aria2 into Conkeror. In this post, I’m going to show a simple tip that can cause aria2 to display notification when it finishes downloading. By default, aria2 provides some input arguments which are the event handlers for download hooks. Those events include --on-bt-download-complete, --on-download-complete, --on-download-error, --on-download-pause, --on-download-start, --on-download-stop. The solution is to pass a shell script to the event and use that bash script to activate notification program. For example

$ aria2c --on-download-complete="/path/to/notification/script.sh" http://example.com/file.iso

You can also pass the event handler command to the aria2 command for starting it as daemon or on RPC protocol. If you are using the command from my previous post, the command will look like this

$ touch /path/to/download/folder/session.txt && aria2c --enable-rpc --rpc-listen-all --save-session=/path/to/download/folder/session.txt --input-file=/path/to/download/folder/session.txt -x16 -s16 -k1M --dir=/path/to/download/folder --daemon --on-download-complete=/path/to/notification/script.sh

When aria2 finishes downloading, it will run the –on-download-complete script and pass 3 arguments, the third one is the path to the downloaded file. The content of the notification script.sh file should look similar to this

#!/bin/sh
notification-command "Download complete $3"
Read more

1. PassportJS

PassportJS is an authentication module for NodeJS which uses the standard Connect middleware structure. As a result, it is convenient to integrate with any applications that operate on the middleware structure like Express. If you haven’t known about Connect middleware yet, take a look at this post Nodejs with Express - More advanced stuff. Passport supports many authentication methods (strategies) like Local (using username and password), OAuth, OpenID or through Facebook, Google, Twitter,…

To use PassportJS, install it as a dependency for your project

$ npm install --save passport

Next, add this to your main app.js file. Put it after initializing session

var passport = require('passport');

var app = express();

app.configure(function(){

  /* other config goes here */

  // put passport config after this line
  app.use(express.session());

  // passport initialization
  app.use(passport.initialize());
  app.use(passport.session());
});
Read more

One of the most important feature introduced in Javascript ES6 is the Generator function, which provides the ability to suspend the execution of a function. However, not all browsers and platforms support generator right now. Earlier versions of Firefox either had ES6 generators turned off, or supported only old style generators. On Chrome 28, you have to turn on an experimental flag named Enable Experimental JavaScript. Node.js haven’t got generator support until version 0.11.2 and you have to run it with --harmony flag.

You have another option that is to compile the javascript files using Regenerator, an ES6 to ES5 Javascript compiler (Google also has their own compiler called Traceur). Regenerator is available on npm

$ npm install -g regenerator

The command to transform js file is simple. You need to include the runtime file in your result html file.

$ regenerator es6.js > es5.js

If you want Regenerator to include the runtime automatically for you in all files that it generates, use --include-runtime flag

$ regenerator --include-runtime es6.js > es5.js
Read more

Internationalization (i18n) is one essential part of any application. This can be achieved easily in Nodejs with the the module i18n. There is another module called i18n-2, which is based on i18n and designed specifically to work out-of-the-box with Express.js. In this post, I will focus mostly on i18n-2.

First, you need to install i18n-2 using npm

$ npm install --save i18n-2

After that, add these config line into your app.js file. Remember to add it after you have loaded the cookieParser.

app.use(express.cookieParser('your secret here')); // put the config after this line

i18n.expressBind(app, {
  // setup some locales - other locales default to vi silently
  locales: ['vi', 'en'],
  // set the default locale
  defaultLocale: 'vi',
  // set the cookie name
  cookieName: 'locale'
});

// set up the middleware
app.use(function(req, res, next) {
  req.i18n.setLocaleFromQuery();
  req.i18n.setLocaleFromCookie();
  next();
});
Read more

1. Browserify in the command line

Browserify helps you modularize your client side Javascript code using Nodejs require style. It also supports transforming Nodejs modules on npm to browser compatible ones. You can install browserify using npm

$ npm install -g browserify

Writing code with browserify is pretty easy and familiar with Nodejs developers. Just write your code in Nodejs require style and then let browserify handle the rest for you. For example you have 2 files, foo.js and main.js with the content like this

  • foo.js
module.exports = function() {
    // do something and return value here
    return 1;
};
  • main.js
// include foo.js here
var foo = require('./foo.js');

// you can also include nodejs/npm modules. this example includes d3-browserify installed
// using npm (npm install d3-browserify)
var d3 = require('d3-browserify');

// call the foo function
foo();  // returns 1

// call the d3
var tree = d3.layout.tree(); // create a tree layout in d3
Read more

Full series: Building website with Nodejs - A post from my experience
Previous post: Nodejs - Express with ejs/stylus basics

Middleware

Simply, middleware are just functions for handling requests from client. Each request can have be associated with a stack of middleware. That means when you have several of handler functions associated with one request, they will be executed sequentially. Back to the example from my previous post

app.get('/', middleware1);

function middleware1(req, res){
  res.render('index', { title: 'Express', check: true });
};

In this example, there is only one middleware (handler) function for the GET request to /. Now we will add one more middleware, or maybe more if you want

app.get('/', middleware1, middleware2);

function middleware1(req, res, next){
  // do something here
  // ...

  // activate the next middleware, otherwise, the next middleware will never be
  // called and the client will wait until timeout
  next();
};

function middleware2(req, res){
  res.render('index', { title: 'Express', check: true });
};
Read more