Node.js on IBM i: Jiving with JavaScript

Programming - Other
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

This will be a “bait and switch.” You know, like that $50 mobile phone plan that gives you “unlimited” calling, data, and texting, as long as you are on a public Wi-Fi? Doh! Well, in this case, the “bait” was dangling “Node.js” in front of you, and the switch is jumping right into ... JavaScript.

Editor's Note: This article is excerpted from chapter 10 of Open Source Starter Guide for IBM i Developers, by Pete Helgren.

The reason for the switch is that there is no “Node.js” language. Here is the definition of Node.js from Wikipedia:

“In software development, Node.js is an open-source, cross-platform runtime environment for developing server-side applications. Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript. The runtime environment interprets JavaScript using Google’s V8 JavaScript engine.”

So, let’s unpack that. Open source: check! Cross-platform: Yep! Otherwise we’d be talking about ILE RPG as the language. And then the mouthful: “runtime environment for developing server-side applications.”

So the first thing to pay attention to is the mention of “server.” Node.js is a server just like your IBM i is an application server. If you happen to use Tomcat or PHP on your IBM i, those are application servers as well. It gets to be a little like those Russian matryoshka dolls that are nested inside of each other: you have an IBM i (server) running Node.js (server), which may be running the plug-in called http-server (server). The operative words to pay attention to are “server” and “Web” and “JavaScript.” I personally think that is where the great utility comes into play. In Node.js, you have a server platform that can serve Web content, and it is a server that uses JavaScript as the base language. As a Web developer, you’ll be bumping into JavaScript basically everywhere, so being able to leverage a language like JavaScript in your “regular” development is a plus in my opinion.

So because Node.js is a server that runs JavaScript, we are going to 1) go through the basics of the JavaScript language and 2) talk about “plugging in” modules in Node.js and how to maintain and write modules for Node.js. Then once we have background on the language, we will walk through our “usual” routine of accessing “local” system commands (PASE in our case), accessing database resources in DB2 for IBM i land, accessing the IBM i command line, and finally making calls to the big wide world of RPG!

Jiving with JavaScript

JavaScript in the Web world has had, and some say still has, a checkered past. Reviled in the late 1990s because of the ease with which it could be exploited for malicious purposes on the Web, it is now, remarkably, the core language for a Web server (Node.js!). The “exploit” side of things is still a risk, primarily in the browser, but the ease with which you can grasp the basics of the language, the plethora of examples and tutorials that exist for free on the Web, and the current romance that the bleeding-edge Web developers have with Node.js make it a great choice for developers looking to add some “dev cred” to their resumes.

JavaScript’s most well-known characteristics are that it is a high-level language (which makes it almost self-documenting), is untyped (which we will talk about), interpreted (which is changing), and is object-oriented (where the power resides!). It is easy to learn, requires no real IDE to use in development (a text editor is enough), and can be run from an HTML form in almost any browser.

Although scripting languages have been around for ages (BASIC and BasicScript come to mind), the rise of using a scripting language in a Web environment coincided with the rise of the Web. For those who are old enough to remember those early days, the 800-pound gorilla of browsers was from Netscape, and those folks developed the first versions of what we call JavaScript today. Microsoft developed VBScript and JScript for the Internet Explorer browser, but Netscape submitted the specification of JavaScript to ECMA, which established an ECMAScript (ES) standard that lives on today. So as of this writing, ES6 is the nascent version now being adopted, ES7 has been released (aka ES 2016), and ES 2017 is in the pipeline. In 2016, the naming and versioning plan changed, and the plan now is to release versions more quickly, perhaps annually, so I wonder, what is the version you will use in 2025?

If you want to “run” a JavaScript script, you have a few choices. A browser can be used if you embed the JavaScript in an HTML form and then use the debugging or developer tools to monitor output. Of course, an easy solution is to run Node.js. For the more adventuresome, you can compile or find a binary for the Google V8 engine and run it in the command window or terminal. For the examples we’ll be running, I am using the Sublime Text text editor, which uses my installed version of Node.js for the runtime environment. There are also other scripting shells available that you can find on the Internet. A scripting shell is also known as a REPL: Read, Evaluate, Print, Loop. In any case, I highly recommend finding something to run the examples with. Trial and error is a great teacher.

JavaScript is both an object-oriented (OO) and a procedural language. You can structure your code however you want (similar to PHP). So, the good news for an RPG programmer is that you don’t have to fully embrace OO techniques in order to make use of the language. But, we are going to go there anyway because it’s cool and productive, and even more so, most code you will come across in the Node.js world will be OO. So put on your “big kid” pants, and let’s start!

Take a look at this example:

Node.js on IBM i: Jiving with JavaScript - Figure 1

The output would be:

Joe Zablotnik:

Joe Zablotnik age is 40

and Joe Zablotnik lives at 123 main street

Pikofp Andropoff:

Pikofp Andropoff age is 30

and Pikofp Andropoff lives at 444 Gorby street

If you wanted to retrieve and print 100 names and addresses in this way, it would be pretty tedious.

Take a look at this alternative:

Node.js on IBM i: Jiving with JavaScript - Figure 2

You say to yourself, “Pete is a genius! He went from 15 lines of code to 21. He must be paid by the line!” Well, that isn’t true, but you still might be scratching your head about how the alternative presented here is “better.” The “better” part is revealed as the number of “persons” increases. The function that outputs the information will always stay at six lines while in the original, more procedural approach you will add the four lines of code to output for each new “person” added. Thinking in OO terms, as was described in chapter 5, is what is needed here. The point is to attempt to encapsulate the object concept into your designs.

So, with that brief introduction to the rationale behind OO design, let’s back up a bit and deal with some basic programming concepts in JavaScript: variables (dynamic typing), scope, objects and classes, arrays and hashes, and functions. The other nuts and bolts of programming in JavaScript will be well known to any experienced programmer, so we won’t be jumping in too deeply on either the well-known concepts or the arcana of the language.

JavaScript is a dynamically typed language, so you could do something like this:

Node.js on IBM i: Jiving with JavaScript - Figure 3

The output would be:

He who dies with the most toys wins 42

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

5

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

4

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

3

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

2

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

1

Keep

using

stuff

until

it

is

all

gone.

Stuff

is

now

0

My stuff is all gone!

The thing that is most notable here is that we see a declared variable assigned not only to different values but different types. JavaScript won’t complain about it. I don’t recommend that you take such a cavalier attitude to variable type assignment. I note it because since an error is not thrown when such reassignment takes place, you could end up stomping on a variable, which may come back to haunt you. Like this:

Node.js on IBM i: Jiving with JavaScript - Figure 4

Rarely would you do such a quick reassignment of a variable type, but imagine if you defined a variable called account and assigned it a string account number, but later on in your code you began to use the same variable as an account balance. JavaScript wouldn’t complain, but your users would. It would also be devilishly difficult to debug (take my word for it!). So I do see variable names like str_name and int_balance where the type is part of the variable name. It can be useful.

Scope plays into the whole untyped variable scenario as well. Take this example, for instance:

Node.js on IBM i: Jiving with JavaScript - Figure 5

The output will be:

42

the number is 42

the number is

You start with a variable that has a value of 42. You inadvertently assign it to a string, so you end up with a string, stomping on the original value. That is why you want to do two things on a regular basis: 1) use a variable name that indicates its type (if possible) and 2) always use “var” when defining the variable for the first time. If something weird is happening in your code that seems drop-dead simple, check for scope issues as well. We could rewrite the code above like so:

Node.js on IBM i: Jiving with JavaScript - Figure 6

The output will be:

42

the number is 42

42

That’s better!

So what kind of dynamic data types are most common? I’d say the following are the ones you are most likely to encounter:

  • var int_length = 42; // Number
  • var str_number = "Forty two"; // String
  • var ary_lang = ["RPG", "Ruby", "Python"]; // Array (
  • var person = {firstName:"John", lastName:"Doe"}; // Object (more about this syntax [JSON] later)
  • var bool_true_false = true; // boolean true/false

There are also a couple of constants that you will get familiar with, even though you may not fully understand them at first:

  • undefinedThe variable has no type and no value. Most variables are in this state until assigned a value.
  • nullNo value and type is object. A null value is always an object For example:

Node.js on IBM i: Jiving with JavaScript - Figure 7

JavaScript also has plenty of built-in functions. typeof is one built-in function that retrieves the type of variable you are dealing with. There are built-in math methods you can access from the Math object, like Math.random(), Math.min(), Math.max(), and many more. There are String methods like substring(), indexOf(), slice(), and a host of others. All of this is well documented on the Web. Google is my programming “pair” when I am in development mode.

There are a few things beyond the basics of variable types and methods that you’ll need to wrap your head around. These are pretty common to most OO languages. As I had reviewed in chapter 5, the cool thing about objects in the OO world is that they contain data and methods. They are like mini-programs in themselves, and leveraging the concepts of inheritance and polymorphism can really improve your productivity. Just like modular programming and the concept of code reuse in Don’t Repeat Yourself (DRY) development, leveraging OO concepts can let you focus on writing new code and new routines while leveraging your prior work.

BLOG COMMENTS POWERED BY DISQUS