Gulpjs – A quick Walkthrough

Today i came across with some amazing and powerful features of Gulp.js(Open source). Its a task runner and a powerful feature of nodejs. Gulp uses node.js streams. Its easy to use and have some useful api.

What is Gulp?

Its is a fast and intuitive streaming build tool built on Node.js. Gulp is a Task / Build runner. It uses node.js streams. Its easy to use and have some useful api, and is efficient. Gulp.js makes use of pipes for streaming data that needs to be processed.

How is it useful

Automating common/tedious task while building product(specially fronted) so that you can focus on more important task. There are loads of plugins available here which does various task and help us achieve almost everything. Few common task that i preferably use:

and many more…

Lets go to playground to have some fun.

Prerequisites:

Since it part of node module so we need to install nodejs first. I run on Ubuntu 14.04 OS.

Open the terminal and first install the node.

sudo apt-get update
sudo apt-get install nodejs

Now you need to install the npm which is Node.js package manager, from which one can install modules and packages to use with Node.js.

sudo apt-get install npm

So node is installed by now, you can check it by issuing nodejs -v and npm -v

Installing Gulp:

sudo npm install -g gulp

Then go to your project directory or create a new one, For me my project root directory is `/home/bishwanath/sites/gulp-demo` and run the following command, which will install it locally to the project also make sure you have already created a package.json files at root level. so that all downloaded plugins will be automatically added under  devDependencies because we use --save-dev flag

npm install --save-dev gulp

Start playing with gulp:

Lets create a file gulpfile.js in your project root directory. where we will create tasks and will run then using gulp command

Here is my initial gulpfile.js look like, just for testing purpose, added a default task which log to console 🙂

var gulp = require('gulp');
gulp.task('default', function() {
   console.log("I have configured a gulpfile"); // This will print on console as output
});

Now run this file using below command, make sure you are into your project dir.

# Lets go to the project directory
bishwanath@bishwanath-jha:~$ cd /home/bishwanath/sites/gulp-demo/

# Files in my project root
bishwanath@bishwanath-jha:~/sites/gulp-demo$ ls -all
total 32
drwxrwxr-x 3 bishwanath bishwanath  4096 Feb 19 01:24 .
drwxrwxrwx 9 bishwanath bishwanath  4096 Feb 18 23:44 ..
-rw-rw-r-- 1 bishwanath bishwanath   126 Feb 18 23:48 gulpfile.js
drwxrwxr-x 4 bishwanath bishwanath  4096 Feb 19 01:17 node_modules
-rw-rw-r-- 1 bishwanath bishwanath   131 Feb 19 01:17 package.json

# Lets execute/run gulpfile
bishwanath@bishwanath-jha:~/sites/gulp-demo$ gulp

# Here is the output
[01:31:23] Using gulpfile ~/sites/gulp-demo/gulpfile.js
[01:31:23] Starting 'default'...
I have configured a gulpfile
[01:31:23] Finished 'default' after 90 μs

In case you get below error, please run the fix as i got this on Ubuntu 14.04 and found the fix here


$ gulp

/usr/bin/env: node: No such file or directory

// Fix:run below command

ln -s /usr/bin/nodejs /usr/bin/node

How Gulp Works:

Gulp allows you to input your source file(s), pipe them through a bunch of plugins and get an output at the end, Let’s take a look at an example of what a basic JS uglifying and concating all js files into single js file called app.js with the help of gulp task.

Lets first install gulp plugin called gulp-uglify and gulp-concat


sudo npm install --save-dev gulp-uglify
sudo npm install --save-dev gulp-concat

Then modify the gulpfile as look like as below now


// Load gulp
var gulp = require('gulp');

// Load gulp plugins
var uglify  = require('gulp-uglify');
var concat  = require('gulp-concat');

// Defining a task as JS uglify
gulp.task('uglification', function() {
return gulp.src('./src/js/*.js') // It loads all .js files under /src/js
.pipe(concat('app.js')) // it further concat all files(currently we have three files check git repo below) contents into app.js
.pipe(uglify()) // it further Minify my JavaScript files/removing-spaces or compressing
.pipe(gulp.dest('./build')) // finally place that app.js file into /build directory
});

// Setting default task to run
gulp.task('default', ['uglification']);

Code Description:

The src() method let’s me specify where to find the JavaScript files.

The pipe() method takes the source stream derived from the src() method and passes it to the specific plugin concat(), so concat would receive the source stream and append all files into app.js

The pipe() method takes the source stream derived from the concat() method and passes it to the specific plugin uglify(), so it would receive the file app.js as stream and minify/compress app.js code.

Finally, using Gulp’s dest() method, all.js is written/created to my target folder. The process if very clear and very readable.

Output:

Now run gulpfile again, it will result into a single app.js(combining all js file mentioned in path into one) file under ./build directory. which will contain concatenated and compressed file of all js files under /src/js/.

bishwanath@bishwanath-jha:~/sites/gulp-demo$ gulp
[02:08:01] Using gulpfile ~/sites/gulp-demo/gulpfile.js
[02:08:01] Starting 'uglification'...
[02:08:01] Finished 'uglification' after 92 ms
[02:08:01] Starting 'default'...
[02:08:01] Finished 'default' after 7.48 μs

This is just one use case, we have may other examples use case. will be covering them into other posts, git repository.

Find the source code here on github : https://github.com/bishwanathjha/gulp-demo

PHP 5.6: What’s new features

PHP 5.6 has been released and is one of very important release. It brings the new features and many improvements and few backward incompatibility also.

Among the main features:

  • Constant scalar expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.


const ONE = 1;

// Scalar Expression in constant
const TWO = ONE * 2;
 
class foo {
    // Scalar expression in class property   
    const THREE = TWO + 1;
     
    // Scalar expression in class methods
    public test($a = ONE + self::THREE) {
        return $a;
    }
}
 
echo (new foo)->test()."\n";

 
  • Variadic Functions via “…”

Earlier we were using func_get_args() to get all the arguments available in a function call(where-ever argument length is variable), but with PHP 5.6, this can be removed as we can easily use … operator. We can also type-hint the parameter.

 
<?php
function f($req, ...$params) {
    // $params is an array containing the remaining arguments.
    echo $req . ' : ' .  count($params)
}

f(1);
f(1, 2);
f(1, 2, 3);

Above output

 
1:0
1:1
1:2

  • Argument unpacking via …

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the … operator. This is also known as the splat operator in other languages, including Ruby.

<?
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);

Above output

6
  • Exponentiation via **
    $a = 2 ** 3; // $a = 8, i.e. 2^3
    $b = 2 ** 3 ** 2; // $b is 512 because its parsed as 2 ** (3 ** 2)
    
    
  • Importing namespaced functions and constants

use function and use const. Earlier this operator was used with class only.

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}

  • Large file uploads

Uploads of over 2GB are now accepted

  • php://input is reusable

This means you can read it several times now, and it always reads from the same data, which has resulted in a significant memory usage reduction.

  • Default character encoding

The default character encoding has been set to UTF-8

  • A new command line debugger called phpdbg

Check out what’s new in php 5.6

Backward Incompatible Changes:

  • Array keys won’t be overwritten when defining an array as a property of a class via an array literal.
  • json_decode() is more strict in JSON syntax parsing.
  • Stream wrappers now verify peer certificates and host names by default when using SSL/TLS.
  • GMP resources are now objects.
  • Mcrypt functions now require valid keys and IVs.

Check out changelog List of changes into function in PHP 5.6

How to Import/Export databases in MySQL from command-line

Recently i worked with MySQL import/export databases and i have found some useful commands below:

Export:

  • All databases into sql file using mysqldump tool
mysqldump -u [username] -p --all-databases &gt; /home/username/filename.sql

In case you want to compress at the same time, run below command

mysqldump -u [username] -p --all-databases | gzip &gt; /home/username/filename.sql.gz
  • Single database into sql file using mysqldump tool
mysqldump -u [username] -p [dbname] &gt; /home/username/filename.sql

In case you want to compress at the same time, run below command

mysqldump -u [username] -p [dbname] | gzip &gt; /home/username/filename.sql.gz
  • Single database table into sql file using mysqldump tool
mysqldump -u [username] -p [dbname] [table_name] &gt; /home/username/filename.sql

In case you want to compress at the same time, run below command

mysqldump -u [username] -p [dbname] [table_name] | gzip &gt; /home/username/filename.sql.gz

Import:

  • Database from sql dump
 mysql -u [username] -p [dbname] &lt; /home/username/filename.sql 

or

 mysql&gt; source /home/username/all_databases_export.sql 
  • Single database from the dump(if it contains multiple databases):
 mysql -u [username] -p --one-database [dbname] &lt; /home/username/all_databases_export.sql 

NOTE :

  • While importing some large database i experience below error something as
 ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes 

In this case i just increase the value of –max_allowed_packet(Default=16M) as below command

 mysql -u [username] -p --max_allowed_packet=256M [dbname] &lt; /home/username/filename.sql 
  • Better using absolute paths.

Some useful PHP related links

An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web

http://www.phptherightway.com/

https://phpbestpractices.org/

 PHP Framework Interop Group

http://www.php-fig.org/

PHP Trends, libraries, and freameworks

http://phptrends.com/

Sample code to understand several PHP design pattern

https://github.com/domnikl/DesignPatternsPHP

A curated list of amazingly awesome PHP libraries, resources and shiny things.

https://github.com/ziadoz/awesome-php

The League of Extraordinary Packages

http://thephpleague.com/

A (digital) square where digital companies broadcast the list of tools they are using to realize their products

http://stackshare.io/

How To Set Up Apache Virtual Host on Ubuntu

Apache web server is the most common and popular in web arena. It has an awesome feature of customization and running websites using virtualhosts.

In this article we will know how to setup virtualhost on apache on Ubuntu(14.04 currently i am using). We will setup “test.com” which will actually point to “/home/<username>/sites/test.com/index.html”

Before we start we assume you have root access, if necessary. <username> is basically your system user directory.

Step 1: First create a directory where you put all your source code under your home directory(most common place)


sudo mkdir /home/&lt;username&gt;/sites/test.com

Add an index.html(with some content) file under test.com
Step 2: Create a new virtualhost file copying existing file under directory “/etc/apache2/sites-available”

cd /etc/apache2/sites-available
cp 000-default.conf test.com.conf

Set at-least “ServerName” and “DocumentRoot” variable as below

 ServerName test.com
 DocumentRoot /home/&lt;username&gt;/sites/test.com

Step 3: Add a host entry into your host file locate under “/etc/hosts”

 

sudo vim /etc/hosts

add a line as below
127.0.0.1 test.com

Step 4: Now enable VitrualHost using below command and restart apache

 sudo a2ensite test.com.conf
sudo apachectl restart

Step 5: Open your web browser and hit the url

http://test.com

In case if you get message like “You don’t have permission to access / on this server. “, Please ensure that “test.com” directory permission is set to 0777. Grant the required permission if necessary.