Sunday, February 19, 2017

10 Commandments For The Beginning Node.js Programmer

Or: How To Overcome Your Disdain Of JavaScript




When I first heard of Node.js, I shuddered knowing those two letters after the period meant JavaScript. To be absolutely clear, I have always hated JavaScript, especially as a PHP programmer. A few years ago one would look at JavaScript code and see the var= thrown out on every third line without any seeming logical structure (besides the one which existed in the head of the programmer), it was not only scary, it was just well, just plain wrong. Yet JavaScript would not go away and it was adopted, with the backing of the major-league players in the browser industry, as the de-facto standard for client-side development. Sure they all had differing implementations which made life on the programmer that much more difficult forcing them to account not only for browsers but for version numbers of each browser. Yet, JavaScript proved resilient along with its big brothers of PHP and others on the backend Server side.

I still shudder at JavaScript, and this is coming from a Node.js convert. So why make such a switch? To answer that question is not the scope of this article, however I did arrive at Node.js through its partner, MongoDB. It offered among other things, such as “asynchronous communication”, “port and packet manipulation” and “blazing speed”. Indeed in regard to MongoDB and speed, Node.js simply put PHP to shame. Just as PHP and MySQL are partners, so to is MongoDB and Node.js.

So here are a few pointers based upon some hard-learned lessons cumulated on my journey without a mentor to guide me into Node.js land.

1. Take Time To Understand The Node.js Structure

Do not be tempted, as I was, to turn up your nose, and assume that since what you are coding is essentially JavaScript you can just get away with throwing in enough var= statements to make everything work. It makes no difference if you are used to OOP in PHP or C, or an awesome framework such as Laravel for PHP. Maybe you are a functional programmer or one that is proud of your OOP understanding, or currently working in DevOps. The concepts in Node.js may be the same, but just like any other programming language the implementation is subject to the rules and requirements of the basics.
While I was trying to get a handle on what Node really is and what it can do, I made the mistake of looking for simple examples on the Internet. It seems that thousands of programmers decided that since Node allows for the easy creation of an HTTP server, the example they all seem to give is that of a Chat forum. So for a few days I went away thinking that is what Node.js is good for, and btw who the hell needs YACS (“yet another chat system”)? I soon realized there has to be more to this Node.js insanity then just creating an HTTP server with 5 lines of code.

Node.js is structurally complicated and contains many different facets. It is also an open system where there are literally thousands of libraries to chose from in order to accomplish both mundane and extremely complicated tasks, (more upon modules later in the document). There are many factors to take into account when beginning to code in Node. Do you want synchronous or asynchronous mode? Do you require callbacks and use of promises? Do you need authorization for clients? Yes, all these factors are inherently part of most programming structures today. But in Node you will be expected to handle it all with speed and grace. As I said, Node can be blazingly fast especially when working in tandem with MongoDB. So taking time to introduce yourself to the Node JS structure of doing things will save you, literally, hours and days of frustration down the line. A good place to start is Node documentation itself.

2. Research Native Node Methods Before Looking Elsewhere

While on your mission of discovery, you will quickly learn that Node JS itself contains a plethora of inner classes and methods. (You can, if you wish, substitute the word “libraries” here, but there is no sense hiding my PHP background.) Many of these methods can be taxing to understand for the most experienced of programmers. Just take a look at the API documentation, which is where you should really start. You do not necessarily have to understand everything or memorize all the possibilities and calls. What you really must be aware of and feel comfortable with, is the vast array of Node.js implementations that can be achieved through either direct use of the classes and methods or via a module which will obfuscate the hard work for you.

There is a temptation, which I have seen many Node.js programmers succumb to, to just seek the closest NPM module to accomplish a specific task and “require” it. This may work for some, but following this route is a guarantee that you will only scratch the Node.js surface and possibly cause you to enter into what is known as “callback hell”. Knowing what Node.js can natively do can help you intelligently produce a working scheme for your next project. This knowledge will also help you navigate the minefield of NPM or Yarn modules out there as well. The API documentation will show you the building blocks in Node.js. Once the classes and methods are at least exposed to your personal bank of information you can begin to wrap your mind around how to structure vastly complicated systems, with multiple servers, clusters, shards and security.

3. Learn The Tools Of The Trade — Including Node.js Versions, NPM, Security & Frameworks

One of the most confusing things to the beginning Node.js programmer is the total mess the Node.js foundation has made with version numbers. As one reads through the information you will see v 0.x.x suddenly jump to 6.x and 7.x. It is important to note that for the latest version of node you should actually go to the site itself. Additionally the installation of Node.js with NPM is actually the way it must be installed. If you are dealing with servers (AWS, Azure, your own etc.) find the appropriate instructions based upon your OS. My personal suggestion would be is to install Node.js itself as a global package (not the modules you download later — in 95% of the cases they should be installed in your project root directory and not as global packages on the server.) So once you have NPM you have Node.js — they are both born of the same installation. I should also note here that updating Node.js to a different version is not just download and replace, for this too you will need instructions.

NPM is the module system which allows you access to literally tens of thousands of packages/modules for Node.js, including frameworks and even command line tools. So another item on the list to master is understanding how to find what you need in NPM and making use of it within your Node.js application.

4. Resist The Urge To Go Module-Library-Framework Crazy In Your Code

I mentioned above the temptation of using NPM modules for every task. The use of modules is critical, but keep a handle on how many you are doing a “require” for. Remember, everything exacts a price in memory and speed. Do not only read the introduction to the module but pay attention to the downloads and when it was last updated. Make sure as well it can work with the version of Node.js you are currently using. Each programmer is different, and you may find, as I did, that some excellent modules just do not make sense to your way of thinking. Do not sweat it. In almost all cases there will be more than a few modules published to accomplish the same task, differing in complexity and use.
In other words: Use an NPM or Yarn Module-Library in your code only after you are sure what it really does and if it accomplishes the task required. This means spending time in testing, updating, uninstalling, installing again. Yet it is well worth the time. Also, keep your package.jsonfile up to date with your project, and make sure you save it somewhere. If by some chance your Node.js project gets wiped out or inaccesible, (as happened to me in AWS — don’t even ask!), you will find that package.json file saving you hours.

5. Even Official Documentation Can Be Faulty & Stack Overflow Is Your Best Friend But It Is Not Perfection

As a programmer you already know, or you will discover the world of stackoverflow. Type in any programming question or error in your browser and chances are you will see quite a few links to stackoverflow. Though many times these have actually saved me, keep in mind the people answering questions are not always correct. Not every answer will help you and it is worth looking, if you can, at a few answers on the same subject. Additionally, one of the surprising things I discovered along the way is that even official documentation, in Node.js and in MongoDB can be very skimpy or just downright wrong at times. Lesson to be learned: Do not always expect the correct answer to your specific problem to show up on your screen after a few clicks.

Don’t ignore places like Medium.com either. There is no lack of excellent technology articles on Medium, some with step-by-step instructions or code-snippets which are superb. I myself made use of such an article here on Medium a month or two ago, and it saved me hours and hours of frustration.

6. You Really Do Need To Understand JSON & ES6

If you cannot read and understand the JSON code in the image, and indeed write it yourself, then take a day or so to learn the JSON format. (It should take all of an hour or two actually.) JSON lies at the heart of many commands in Node.js and in the modules, and without knowledge of how it work or what it is used for you are fighting a losing battle. At the very least understand what a JSON object is and what the difference is between JSON.parse and JSON.stringify. (Oh I forgot to warn you about dot notation as well!)

I fully expect to be told this next statement is not true. So let me put this down to a personal favorite. If you are not familiar with ES6 then I strongly suggest you take a look at some of the documentation. If you are an OOP programmer especially in PHP, you will absolutely love ES6. Just let me show the one very minor change in ES6 that made me fall in love with it.
Assume you have a JavaScript string variable which holds the number of articles I published in Medium:

let articleNumMedium = 2363;

Now let us say I want to combine this variable with a string:

This is an article about Node.js and I have now published +
articleNumMedium + articles.;
Now in ES6 with a simple use of a backtick ` and ${} I can now write that out entirely as a string and still have the variable be populated correctly!
`This is an article about Node.js and I have now published ${articleNumMedium} articles` 
→ produces the exact same result as above. “This is an article about Node.js and I have now published 2563 articles.”;

Yay! Finally an end of string concat hell! So yes, just because of this, not to mention the ability to create classes and inheritance, I am in love with ES6! Don’t knock it if you have not tried it.

7. Know Your ABC Of The Stack You Are Creating

Today, I often laugh at the alphabet soup which programming has become. Every day there seems to be another term, technology and accompanying set of initials to learn and discover. You will have to decide yourself what is critical for your project and growth as a programmer and what is not. Despite what others claim, I have never run into a programmer that knows or even wants to know everything in every language. There are the PHP backend lovers, the Python fanatics and the JavaScript adherents. Every single language has its lovers and haters. All that being said, in Node.js I would suggest you pay attention to a few important factors.
  • Understand clearly what your stack will look like even if it is a full MEAN stack or a derivative of it.
  • Know what synchronous and asynchronous modes do and how they affect the methods you write and functions you create. This may be actually one of the most important factors in dealing with Node.js. You really do need to fully understand the synch-async paradigm, how to code in each and what the consequences are.
  • Speaking of consequences, Callbacks & Promises are two which are really important to know. Callbacks are great until you enter into callback hell from so many firing off at once. Promises are also critical. Read or watch visuals on these subjects, but make sure you do understand them and the implications to your code.
  • Threads & Loops are part of any programming structure, and I should not have to spend time explaining why these are important to understand and manipulate. Beware of loops in Node.js. Test, test and test again. Believe it or not, sometimes your best friend is console.log().
  • Middleware is a concept in Node.js you will not be able to avoid, simply due to the enormous popularity of Express & Passport, middleware for Node.js. Understand what it does, why it is so popular and how to use them correctly. I will repeat this again, remember, not everything you read in Stackoverflow will be correct. Take the time to learn, research and understand.
  • 8. Write Code Which Is Clean, Orderly & Documented — Especially Because Node.js Is Essentially JavaScript!

    This is certainly not specific to JavaScript or even Node.js but we all tend to get sloppy with code, especially documenting what is going on within the code. You can use JSDoc for documentation, but as a personal preference I avoid it, probably more out of laziness than anything else.
    • Document all your procedures & functions at least with a line or two, if only to remind yourself, six months from now exactly what you were doing. I am sure you have looked at your code and had a few WTF? moments.
    • Create variable names which actually mean something (foo, bar and fafa are out!). Learn the difference between var=, const= and let=. This means understanding “scoping”.
    • Create orderly file & directory structures. BTW, create file names which actually mean something to you or to the group you work with. (Same rule as with variables.)
    • Indent and re-indent and format your code as much as required. It not only looks pretty but it will help you know what }) and } is missing. I am one of those programmers (probably due to PHP) who makes sure the ; is always there. All I beg of you to do, is once you do decide on a coding style with or without the ; stick to it through the entirety of code. I cannot tell you how many code blocks I have seen where the programmer, even some professionals writing sample code, seem to use the ; on-again, off-again, on-again basis or on some sort of nutty routine that is known only to them. Code like that is horrendous to read or follow
    • You will not, I repeat will not, be considered a king nerd if you do take the time to plan out your theoretical code structure. If your boss is bouncing on your head to get the project done make her/him understand that actual planning is part of the project. Or else just fake typing on the keyboard. That too will work.

    9. Do Not Ignore The Tools & Helpers For Your OS & Node.js

    As a programmer you well know how many tools are out there to make your life easier. In this case I will just mention five that I cannot do without, especially on Linux. (I program on a Mac now, and I really don’t want to get into the PC vs. Mac wars.) Below are current personal favorites, which save me a lot of time. Emphasis on the word personal. If you have others I would love to hear from you. Honestly, I love learning new tools which are actually useful.
    • Phpstorm as an IDE— Programmers are notorious for their love of one IDE over another. As a PHP programmer I used to use NuSphere. It is also a great IDE. Yet, when it comes to PHP and especially Node.js check out my new love, PhpStorm by Jetbrains. It can be a bit daunting to set up a project initially with all the options, but the learning curve is well worth it. It supports JSLint, JSHint & you can set it to the level of ES you are working with. To be fair you cannot go wrong with NuSphere in PHP, however, I cannot attest to its capabilities in regard to Node.js and JavaScript.
    • Locate — This utility may or may not be on your linux server. If it is not, forget the “find” command and just install locate. 
      1
      2
      sudo yum install mlocate
      sudo updatedb
      
    • Glances — If you have dealt with Linux or Ubuntu for any period of time, you know about processes and the PID. If a service starts running in order to kill it, you have to find the PID, and use a special kill command. This can be a long tedious process. In comes Glances. It really is a robust tool allowing you to view and monitor all the processes running on the server as well as giving you other vital information. However, Glances can be tricky to install on AWS EC2 especially on Linux. If you are working with AWS Linux follow the 3 steps below (which do not seem to be in the official documentation, and makes sure you are updated with Python and pip.)
      1
      2
      3
      sudo yum -y install python-pip
      sudo pip install — upgrade setuptools
      sudo pip install glances
      
    • PM2 — Sooner or later, your programming will grow up, and you will have to deploy your Node.js server(s). This means you need to daemonize the process to make sure if either the server goes goes down and restarts, or if your Node.js server module goes down it will restart automatically. PM2 goes far beyond just that. Of course, if you are already a Forever freak, forget the PM2.
    • Bash — If you use Bash, and I am not telling you to leave your favorite terminal editor, then also take the time to learn how to set up your terminal (on the Mac go to Terminal → Preferences). Also read up on how to configure your .bash_profile. Just creating an alias or function will save you thousands of keystrokes.

    10. Admit To Yourself That You Are Now Coding In JavaScript

It is time to face the music. You are now a JavaScript & Node.js programmer. Since var= has been replaced with let= and const= you will not be wading in var= statements anymore, (though let= may take its place very soon!) Yesterday you were a cool, smart OOP programmer writing this=>all over the place. Classes, Methods & Functions still exist in your world of Node.js you just have to understand how to implement them.
Still in the end, after all is said and done, you are now one of those JavaScript programmers who we once ridiculed and laughed at. Take heart though. With a few {{}} and “var” and “let” everything can be solved. Bet you can’t do that in PHP (even if you do use Laravel)!

No comments:

Post a Comment

All comments are moderated simply to avoid spam. Thank you.