22
Fri, Nov
1 New Articles

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.

Peter Helgren

Peter Helgren is programmer/team lead at Bible Study Fellowship International. Pete is an experienced programmer in the ILE RPG, PHP, Java, Ruby/Rails, C++, and C# languages with more than 25 years of system 3X/AS400/iSeries/IBM i experience. He holds certifications as a GIAC certified Secure Software Programmer-Java and as an MCSE. He is currently executive vice president on the COMMON Board of Directors and is active on several COMMON committees. His passion has always been in system integration, and he focuses on open-source applications and integration activities on IBM i. Pete is a speaker/trainer in RPG modernization, open-source integration, mobile application development, Java programming, and PHP and actively blogs at petesworkshop.com.


MC Press books written by Peter Helgren available now on the MC Press Bookstore.

Open Source Starter Guide for IBM i Developers Open Source Starter Guide for IBM i Developers
Check out this practical introduction to open-source development options, including XMLSERVICE, Ruby/Rails, PHP, Python, Node.js, and Apache Tomcat.
List Price $59.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: