dreamsys software

JavaScript Shell Scripting Tutorial

If/Else


In order for a script to be very useful, you will need to be able to test the conditions of variables. Most programming and scripting languages have some sort of if/else expression and so does JavaScript. Like other languages, spaces and returns are not important when using an if statement, their blocks of code are contained within curly braces {}. Let's do a simple script that will ask a user for a password before allowing him to continue. This is obviously not how you would implement such security in a real system, but it will make a good example of using if and else statements.

#!/usr/bin/env node

var validPassword = 'secret'; //This is our secret password...

console.log('Enter the password to continue: ');

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
        var inputPassword = chunk.trim();

        if (inputPassword == validPassword) {
                console.log('You have access!');
        } else {
                console.log('Access Denied!');
        }

        process.exit();
});

In this example, the "is equal to" comparison is used in the if condition. This is represented by the "==" operator. If you wanted to do the check "is not equal to", you could use the operator "!=". Below is a table of some of the comparisons you can use in your scripts:

Comparisons:
==equal to
!=not equal to
<less than
<=less than or equal to
>greater than
>=greater than or equal to

There are several new things in this script, first we want to initialize stdin (Standard Input) by calling process.stdin.setEncoding('utf8');. This will ensure the encoding of input strings is UTF-8. Next we create an function handler that is fired on a data event. We will cover functions in more detail later, but for now, just understand that we are passing a function which gets a value chunk set as the input the user types on the console. Whenever this event is fired by the user pressing return, this function will be called.

Now that we have our chunk of data, first we need to trim off the excess return key at the end, so we create a new variable called inputPassword and give it the value of the chunk variable after calling the trim string function on it. The trim function removes any whitespace characters before and after a string.

The next step is to do the actual comparison, which is done in the if statement using the == operator. Finally we need to call process.exit() because this event handler will keep the script open waiting for more input.

Let's enhance our years.js script to include some better checking. This time we will prompt for the variables if they are not given on the command line.

#!/usr/bin/env node

var prompt = require('prompt');

prompt.start();

prompt.get(['name', 'age'], function (err, result) {
        if (err)  throw err

        var sayAge = ''

        if (result.age == 100) {
                sayAge = 'You are already 100 years old!';
        } else if (result.age < 100) {
                sayAge = 'You will be 100 in ' + (100 - result.age) + ' years!';
        } else {
                sayAge = 'You turned 100 ' + (result.age - 100) + ' years ago!';
        }

        console.log('Hello ' + result.name + ' ' + sayAge);

});

In this script, we are introducing a new concept of requiring node modules. In the first part of the script, notice that we are calling the function require('prompt'). This cases the script to import the node module named "prompt" and assign it to a variable, which we aptly named "prompt" as well. In order to this however, you must first install the module using the node package manager npm using the following command:

npm install prompt

After running this command you can successfully import the node module using the require function as seen in the script. The prompt module is a very useful utility that allows you to specify the variable names you want created and will create prompts for each of those variables. This script also introduces a new keyword, else this is the code that is executed if the if statement does not pass. Notice that our if conditions now has 3 checks, if the age is 100, if the age is less than 100, and everything else (age > 100). We could have put else if age > 100 in place of the else keyword, but they would do the same thing in this situation.

Now that our script is complete, we can move on to more interesting topics. In the next section we will cover looping.

Prev (Variables) | Next (Looping)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6