dreamsys software

JavaScript Shell Scripting Tutorial

Classes


When your scripts start to grow and your set of functions grow, you will start to notice that many of your functions are related, they work on data that is common between them and they really represent an entity collectively. This is where it is usually a good idea to create a class. Let's say that our program, deals with a user name, age, birth date, height, weight and variables like that and there are methods in our program such as readUserAge, readUserName, updateUserAge, etc. A good place to start would be to add a class "User" which is done by using the function keyword. In JavaScript a "class" is actually a function that contains data and other functions.

Now let's create a simple script which will ask the user for information on a user, store it to a file and load the user info from the file. We will have it run with two options, one is that the user enters the info, and another is that it just loads the user from the file and displays it.

Note: We will be using the "prompt" node module again, so be sure to first run npm install prompt before running the script.

#!/usr/bin/env node

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

prompt.start();

function User() {
	var self = this;

	self.name = '';
	self.age = 0;
	self.height = 0;
	self.weight = 0;

	self.display = function() {
		console.log('');
		console.log('User Information:');
		console.log('User Name     : ' + self.name);
		console.log('User Age      : ' + self.age);
		console.log('User Height   : ' + self.height);
		console.log('User Weight   : ' + self.weight);
	}

	self.loadFromInput = function() {
		prompt.get(['name', 'age', 'height', 'weight'], function(err, result) {
			if (err) throw err;

			self.name = result.name;
			self.age = result.age;
			self.height = result.height;
			self.weight = result.weight;

			self.save();
		});
	}

	self.loadFromFile = function() {
		var lines = fs.readFileSync('user.txt').toString().split('\n');
		self.name = lines[0];
		self.age = lines[1];
		self.height = lines[2];
		self.weight = lines[3];
	}

	self.save = function() {
		fs.writeFile('user.txt', self.name + '\n' + self.age + '\n' +
				self.height + '\n' + self.weight, function(err) {
			if (err) throw err;
			console.log('user saved');
			self.display();
		});
	}
}

var args = process.argv.slice(2);


if (args.length >= 1 && args[0] == 'READ') {
	var user = new User();
	user.loadFromFile();
	user.display();
} else {
	var user = new User();
	user.loadFromInput();
}

the first new thing you will notice here is that we are creating a function called "User" and this function contains more functions. This is how you do a class in javascript. First in the User "class" you see that we create a variable named "self" and assign the value of "this" to it. This is a pointer to the current object/function and we put it in a variable because "this" can point to different things when used inside sub-functions. Now, what does the user have? It has a name, age, height and weight. We define these at the top so they are clear. What do we want to do with a user? We want to load it from a file, load it from user input, save it and display it. So there are functions for each of these operations.

We declare class functions the same as we do regular functions except that they are under the class level. The functions can be declared in any order but here we have ordered them in the order that they will typically be called.

In the display() function, we are simply printing the data of the class, notice that we use the self variable before the variable name. The loadFromInput() function uses the prompt node module that we are already familiar with to load the user info from the console input.

The save() method uses a new module, fs, which can be used to interact with the file system. In the save method, we use the writeFile method which writes data to a file asynchronously. We provide it will a callback function. If that function has set the "err" variable to a value, then we know it failed.

Finally, the loadFromFile() method will open the file in read mode by using the function readFileSync. This will read the file synchronously, create it as a string using toString and then split it into an array by the return character. Now that we have the array, we can assign each of the properties of the class to the lines in the file.

Below the class we show how the class is actually used. First we do an if statement to find out if there is a parameter to the script. If so, we validate also that it is the value "READ", if so then we want to read the user from the file. Otherwise, we know that we need to create the file based on user input.

Notice that we create a variable named "user" and assign it to "new User()". This creates an instance of the class that we can then call functions on. So we create this user object and call loadFromFile() followed by display(). Likewise we call loadFromInput() if that is the chosen option.

So now, let's run the script once to create the user and then again to read the user from the file:

$ ./userTest.js
prompt name: Joe
prompt age: 25
prompt height: 5.9
prompt weight: 170

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170
$ ./userTest.js READ

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170

There are more ways you create a class in JavaScript. Another option is to use the prototype keyword. Next you will learn how to manipulate strings.

Prev (Functions) | Next (Strings)


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