Sidebar

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

More Articles By This Author
Related Articles
BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

RESOURCE CENTER

  • WHITE PAPERS

  • WEBCAST

  • TRIAL SOFTWARE

  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things


    Read Node.js for Enterprise IBM i Modernization Now!

     

  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!

     

  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.

     

  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.

     

  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact

     

  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using NodeRun.com as a pre-built development environment

     

     

  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.

     

     

  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.

     

     

  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails

     

  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.

     

     

  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.