Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Hooks With Apache Cordova Mobile Applications

TwitterFacebookRedditLinkedInHacker News

If you develop Apache Cordova applications long enough, you’re eventually going to notice little things that you feel you can improve in the development / deployment lifecycle. Making use of hooks in your Apache Cordova project can yield many great things for your project.

Hooks are scripts that are run at various times in the build process. According to the Apache Cordova documentation there are thirty-two different hook types. A few of the possible hooks are as follows:

  • before_prepare
  • after_prepare
  • before_build
  • after_build

In this example, we’re going to see how to make a very simple Apache Cordova hook that removes temporary files from a project before preparing to build. Although not incredibly useful, it does serve a purpose and can definitely reduce junk in your project.

Let’s start by creating a fresh Apache Cordova project for Android or iOS:

cordova create TestProject com.nraboy.testproject TestProject
cd TestProject
cordova platform add android
cordova platform add ios

Note that if you’re not using a Mac, you cannot add and build for the iOS platform.

In this particular example we will be creating a before_prepare hook in Node.js. In the hooks directory at the root of your project, if the before_prepare directory does not exist, go ahead and create it. Any script to be run before preparing our files will be placed in this directory.

Scripts in the hooks/before_prepare directory will execute in an order based on their file name. Our junk clean up script should be one of the first ones run, so create a file named 01_junkcleanup.js in the before_prepare directory. A common problem with Apache Cordova hooks is that they require certain file permissions on Linux and Mac operating systems. Without the execute permission, they will not run.

Execute the following to make sure we have the correct permissions:

chmod 777 hooks/before_prepare/01_junkcleanup.js

It is now time to add some code to our script.

#!/usr/bin/env node

var fs = require('fs');
var path = require('path');

var foldersToProcess = [
    "js",
    "css"
];

foldersToProcess.forEach(function(folder) {
    processFiles("www/" + folder);
});

function processFiles(dir) {
    fs.readdir(dir, function(err, list) {
        if(err) {
            console.log('processFiles err: ' + err);
            return;
        }
        list.forEach(function(file) {
            file = dir + '/' + file;
            fs.stat(file, function(err, stat) {
                if(!stat.isDirectory()) {
                    switch(path.basename(file)) {
                        case ".DS_Store":
                            fs.unlink(file, function(error) {
                                console.log("Removed file " + file);
                            });
                            break;
                        case "Thumbs.db":
                            fs.unlink(file, function(error) {
                                console.log("Removed file " + file);
                            });
                            break;
                        default:
                            console.log("Skipping file " + file);
                            break;
                    }
                }
            });
        });
    });
}

Let’s break down what the above script means.

var foldersToProcess = [
    "js",
    "css"
];

foldersToProcess.forEach(function(folder) {
    processFiles("www/" + folder);
});

I’ve gone ahead and determined that we should be checking the js and css directories in the www directory, found in the root of your project, for junk files. You can feel free to add more or less. Because we are shooting for simplicity, no recursion will take place, so only files found at the root of these directories will be examined.

In the processFiles(dir) method, we will loop through each file found in the directory. This includes directories, even though we won’t be looking at them.

switch(path.basename(file)) {
    case ".DS_Store":
        fs.unlink(file, function(error) {
            console.log("Removed file " + file);
        });
        break;
    case "Thumbs.db":
        fs.unlink(file, function(error) {
            console.log("Removed file " + file);
        });
        break;
    default:
        console.log("Skipping file " + file);
        break;
}

The above code will determine which files get deleted or skipped. By default, the files will not be touched, however if anything shows up in our switch that is not considered default, it will be unlinked / deleted from the file system.

The Apache Cordova hook we just created will be run under multiple circumstances. We can execute it directly by running cordova prepare from the command line or by running cordova build [platform] since the build process makes a call to the prepare scripts as well.

To re-iterate, this particular hook will get rid of temporary files or garbage that gets placed by the operating system.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.