Monthly Archives: October 2019

The Node.js Update #Week 42 of 2019. 18 October

By Ferenc Hamori

The Node.js Update #Week 42 of 2019. 18 October

Below you can find a collection of the most important Node.js updates, tutorials & announcements from this week – curated by RisingStack’s Node.js Consultants.

Latest Node.js Updates here: 10.16.3 LTS / 12.12.0 Current

First, let’s start with “official” Node news:

Node v12.12.0 Current Released. Changelog:

  • build: Add –force-context-aware flag to prevent usage of native node addons that aren’t context aware
  • deprecations: Add documentation-only deprecation for process._tickCallback()
  • esm: Using JSON modules is experimental again
  • fs: Introduce opendir() and fs.Dir to iterate through directories
  • process: Add source-map support to stack traces by using --enable-source-maps
  • tls:
    • Honor pauseOnConnect option
    • Add option for private keys for OpenSSL engines

Node.js 13.0.0 (Current)

Did you know that you can already check out Node 13?

GitHub Package Registry Beta Announcement

With the GitHub Package Registry you can safely publish and consume packages within your org.

npm is moving back to its developer roots, founder says

According to Isaac Schlueter, the right strategy for “building a sustainable engine behind an open source labor of love” might well be a return to npm’s roots.

Awesome Node.js & JavaScript Tutorials:

Build a Stripe Billing onboarding flow with Node and React

In this article we will be going over the steps needed to integrate Stripe Billing with an onboarding flow using Node.js and React. In the guide we will be:

  • Configuring a Stripe account with a pricing strategy we will be using in this example
  • Setting up a Route in ExpressJS which will expose the pricing strategy to the front-end
  • Setting up a React front-end which will handle the onboarding flow, utilizing Stripe Elements for checkout

Build Command-Line Spinners in Node.js

Practice your Node.js-terminal skills by building your own CLI spinners.

Coloring Your Terminal Using Nodejs

Chalk has been the most widely used library for adding color effects on our Node CLI project. Most people are unaware of how Sindre Sorhus implemented the library, so I decided to take my time out to write about it.

In this post, we will see how to write colors to our terminal using Nodejs.

The Power of JSON.STRINGIFY replacer parameter

I had an interesting problem that melted my brain a bit. Let me share what I have learned and maybe save you a few moments when you come across a similar challenge.

Continuation Local Storage for easy context passing in Node.js

Recently I’ve been working on a Node.js project where we needed to keep track of which requests were generating calls to some other pieces of code. Passing a request identifier around was not viable since it would require to change too many APIs.

We solved the problem using cls-hooked, a small package that uses the async_hooks experimental Node.js API to implement Continuation Local Storage.

The perfect architecture flow for your next Node.js project

We can all agree that our project architecture is extremely important, and we can also declare a few points that can help us determine what this architecture must help us do:

  • Achieve clean and readable code
  • Achieve reusable pieces of code across our application
  • Help us to avoid repetitions
  • Make life easier when adding a new feature into our application

Interesting JS & Node Discussions:

7 Simple but Tricky JavaScript Interview Questions

Do people really ask questions like these?

npm is moving back to its developer roots, founder says

Hard times for npm when github prepares to step in.

Should We Rebrand JavaScript?

Recruiters are still confusing Java and JavaScript…

Source:: risingstack.com

Fun, Fast, and Free Login with React Native

By Matt Raible

React Native is a mobile app development framework that allows you to use React to build native iOS and Android mobile apps. Instead of using a web view and rendering HTML and JavaScript, it converts React components to native platform components. This means you can use React Native in your existing Android and iOS projects, or you can create a whole new app from scratch.

In this post, I’ll show you how to add a login feature to a React Native application using OAuth 2.0 and OpenID Connect. Authentication and authorization are important parts of most applications as you often need to know who a user is (authentication) and what they’re allowed to do (authorization). OAuth 2.0 is an industry-standard protocol for authorization and OpenID Connect (OIDC) is an authentication layer on top of OAuth 2.0. Integrating with an always-on service like Okta for OAuth makes set up and configuration easy, particularly with React Native and Okta’s React Native SDK.

React Native 0.61

Source:: scotch.io

Vanilla JavaScript and HTML - No frameworks. No libraries. No problem.

By John Papa

Vanilla JavaScript and HTML - No frameworks. No libraries. No problem.

Are you using Vue, React, Angular, or Svelte to create web apps? I am, and if you are too, I bet it’s been a while since you’ve written an app that renders content without these fine tools.

Armed with only what comes with the browser. Years ago this is exactly how many of us wrote web apps. While today’s tools help abstract that away (and add a bunch of other benefits), it is still useful to know what is happening under the covers.

Also, consider that if you are rendering small amounts of content you may want to just use HTML. JavaScript and the DOM without any other tools. Recently I wrote some web fundamentals examples to help teach the DOM, HTML, JavaScript, and the basics of the browser. This experience made me realize that maybe other developers, maybe you, would appreciate a reminder of how you can render content without libraries.

If anything, it’s fun, educational, and might make us all respect the value of modern libraries and frameworks which handle this for us.

With that, let’s explore a few different ways you can render content. Oh, and keep those MDN Web docs handy!

The Sample App

Here is the app I’ll demonstrate in this article. It fetches a list of heroes and renders them when you click the button. It also renders a progress indicator while it is fetching.

Vanilla JavaScript and HTML - No frameworks. No libraries. No problem.

Tools

The right tools are important, and in this exercise we want to render some content to the browser using the basic tools that we all have. No frameworks. No libraries. No problem.

All we get to use are HTML, TypeScript/JavaScript, CSS, and the browser DOM (document object model). Now let’s get to work and see how we can render HTML.

If you look closely, you may see I’m using TypeScript in the code. I’m using it because it is super helpful at avoiding bugs due to it’s typings and I get to take advantage of how it transpiles to any JavaScript format I need. You could 100% use JavaScript if you prefer. I’ll write more in a future article (soon) about how you can transpile TypeScript too.

The Approach

This sample app renders a list of heroes and a progress indicator (while it is working). Let’s start by exploring the simpler of these, the progress indicator, and show various ways in which it can be rendered. Then we’ll shift to the list of heroes, and see how things change (or not) when there is more to render.

Rendering Progress Indicators

The progress indicator should appear while the app is determining which heroes to render. So it will not be visible until the refresh button is clicked, then it will appear, and finally disappear after the heroes render. Let’s explore a few ways this can work.

All of the techniques require some awareness of where to put the elements as they are built. For example, the progress indicator and the heroes list both have to go somewhere. One way to do this is to reference an existing element which will contain them. Another way is to reference an element and replace that element with the new content. We’ll see a little of each throughout this article.

Rendering Progress with Inner HTML

Create HTML and put it inside of another element. This is one of the oldest techniques, but hey, it works! Locate the element where the progress indicator will go. Then set it’s innerHtml property to the new content. Notice we’re also trying to make it readable using template strings that allow it to span multiple lines.

const heroPlaceholder = document.querySelector('.hero-list');
heroPlaceholder.innerHTML = `
  <progress
    class="hero-list progress is-medium is-info" max="100"
  ></progress>
`;

Simple. Easy. Why isn’t all code like this? I mean, come on, look at how quick this code solves the problem!

Alright, you’re probably already thinking ahead at how fragile this code can be. One mistake in the HTML, and bam! We have a problem. And is it truly readable? This code is arguably readable, but what happens when the HTML becomes more complex and you have 20 lines of HTML and classes and attributes, and values and … you get the point. Yeah, this is not ideal. But for short bits of HTML, it does work and I wouldn’t cast it aside too quickly for one liners.

Something else to consider is how embedded content might add to the readability and stability of the code. For example, if you add content inside of the progress bar for a loading message that changes, you could do this using the replacement technique like this ${message}. This isn’t good or bad, it just adds to your considerations when creating large template strings.

One last point on innerHTML is that performance in rendering “may” be a concern. I say this because I do not subscribe to over optimization. But it is worth testing the performance of rendering HTML using innerHTML as it can cause rendering and layout cycles in the browser. So keep an eye on it.

Rendering Progress with the DOM API

One way to reduce some of the clutter of the long strings is to use the DOM API. Here you create an element, add any classes it needs, add attributes, set values, and then add it to the DOM.

const heroPlaceholder = document.querySelector('.hero-list');
const progressEl = document.createElement('progress');
progressEl.classList.add('hero-list', 'progress', 'is-medium', 'is-info');
const maxAttr = document.createAttribute('max');
maxAttr.value = '100';
progressEl.setAttributeNode(maxAttr);
heroPlaceholder.replaceWith(progressEl);

The upside here is that the code has more typing and it relies on the API. In other words, if something was typed wrong, the chances are higher in this code than that of the innerHTML technique that an error will be thrown that will help lead to the problem and solution.

The downside here is that this it took six lines of code to render what took one line with innerHTML.

Is the DOM API code more readable than the innerHTML technique to render the progress bar? I argue that it is not. But is that because this progress bar HTML is super short and simple? Maybe. If the HTML were 20 lines, the innerHTML would be less easy to read … but so would the DOM API code.

Rendering Progress with Templates

Another technique is to create a tag and use that make it easier to render content.

Start by creating a and giving it an id. The template will not render in the HTML page, but you can reference it’s contents and use those later. This is very useful so you can write the HTML where it makes the most sense: in the HTML page with all the helpful features of an HTML editor.

<template id="progress-template">
  <progress class="hero-list progress is-medium is-info" max="100"></progress>
</template>

Then the code can grab the template using the document.importNode() method of the DOM API. It can manipulate the content in the template, if needed (in this case there is not need). Then add that content to the DOM to render the progress bar.

const heroPlaceholder = document.querySelector('.hero-list');
const template = document.getElementById('progress-template') as HTMLTemplateElement;
const fetchingNode = document.importNode(template.content, true);
heroPlaceholder.replaceWith(fetchingNode);

Templates are a powerful way to build HTML. I like this technique because it let’s you write HTML where it makes sense and the TypeScript/JavaScript code is doing less.

You might wonder if you can import templates from other files. The answer is that you can, but using other libraries. But this exercise is sticking with no libraries. Natively there has been discussion about HTML imports for years, but as you can see in the “Can I Use” site, the support is not quite there yet in most modern browsers.

Render a List of Heroes

Let’s shift to how we can render the list of heroes using those same three techniques. The differences here from rendering a single HTML element and rendering a list of heroes are that we are now rendering:

  • multiple HTML elements
  • adding multiple classes
  • adding child elements, a specific sequence
  • rendering a lot of similar content, for each heroes
  • displaying dynamic text inside of elements

Render Heroes with Inner HTML

Using innerHTML it makes sense to first start with the array of heroes and iterate through them for each hero. This will help build each row, one at a time. The rows are identical other than the hero’s name and description, which we can insert using template strings. Each hero in the array builds up a

  • , which is then mapped to a rows array. Finally, the rows array is transformed into the raw HTML, wrapped with a
      , and set to the innerHTML.

      function createListWithInnerHTML(heroes: Hero[]) {
        const rows = heroes.map(hero => {
          return `<li>
              <div class="card">
                <div class="card-content">
                  <div class="content">
                    <div class="name">${hero.name}</div>
                    <div class="description">${hero.description}</div>
                  </div>
                </div>
              </div>
            </li>`;
        });
        const html = `<ul>${rows.join()}</ul>`;
        heroPlaceholder.innerHTML = html;
      

      Again, this works. And it is “arguably” quite readable. Is it the most performant? Is it ripe with possible typing mistakes that won;t be caught easily (or ever)? You be the judge. Let’s hold judgment until we see some other techniques.

      Rendering Heroes with the DOM API

      function createListWithDOMAPI(heroes: Hero[]) {
        const ul = document.createElement('ul');
        ul.classList.add('list', 'hero-list');
        heroes.forEach(hero => {
          const li = document.createElement('li');
          const card = document.createElement('div');
          card.classList.add('card');
          li.appendChild(card);
          const cardContent = document.createElement('div');
          cardContent.classList.add('card-content');
          card.appendChild(cardContent);
          const content = document.createElement('div');
          content.classList.add('content');
          cardContent.appendChild(content);
          const name = document.createElement('div');
          name.classList.add('name');
          name.textContent = hero.name;
          cardContent.appendChild(name);
          const description = document.createElement('div');
          description.classList.add('description');
          description.textContent = hero.description;
          cardContent.appendChild(description);
          ul.appendChild(li);
        });
        heroPlaceholder.replaceWith(ul);
      }
      

      Rendering Heroes with Templates

      The heroes list can be rendered using templates, using the same technique we used to render the element. First, the template is created in the HTML page. This HTML is slightly more complex than what we saw with the element. You can easily imagine how even more HTML would not be a problem using this technique. it’s just HTML in an HTML page, with all the benefits of fixing errors and formatting with a great editor like VS Code.

      <template id="hero-template">
        <li>
          <div class="card">
            <div class="card-content">
              <div class="content">
                <div class="name"></div>
                <div class="description"></div>
              </div>
            </div>
          </div>
        </li>
      </template>
      

      You could then write the code to create the heroes list by first creating the

        to wrap the heroes

      • rows. Then you can iterate through the heroes array and grab the same template for each hero, using the document.importNode() method once again. Notice the template can be used repeatedly to create each row. One template becomes the blueprint for as many here rows as you need.

        The heroes list should show each respective hero’s name and description. This means that the template only gets you so far, then you have to replace the hero specific values inside of the template. This is where it makes sense to have some way to identify and reference the places where you will put those hero specific values. In this example, the code uses the querySelector('your-selector') method to get a reference for each hero, before setting the name and description.

        function createListWithTemplate(heroes: Hero[]) {
          const ul = document.createElement('ul');
          ul.classList.add('list', 'hero-list');
          heroes.forEach((hero: Hero) => {
            const template = document.getElementById('hero-template') as HTMLTemplateElement;
            const heroCard = document.importNode(template.content, true);
            heroCard.querySelector('.description').textContent = hero.description;
            heroCard.querySelector('.name').textContent = hero.name;
            ul.appendChild(heroCard);
          });
          heroPlaceholder.replaceWith(ul);
        }
        

        Is the template easier than the other techniques? I think “easy” is relative. I personally feel that this code follows a pattern that is fairly repeatable, readable, and less error prone than the other techniques.

        Summary

        Notice I have not mentioned how the major frameworks and libraries handle rendering content. Vue, React, Angular, and Svelte all make this significantly easier using less code. They also have their own respective additional benefits beyond rendering. This article is only focusing on the a relatively simple rendering using the DOM with pure HTML and TypeScript/JavaScript.

        Where does this leave us?

        Hopefully this gives you an idea of how you can render content without any libraries. are there other ways? Absolutely. Can you make reusable functions to make the code simpler and more reusable? Absolutely. But at some point you may want to try one of the very awesome framework tools such as Vue, React, Angular, or Svelte.

        These popular frameworks are doing a lot for us. If you are like me, you recall using pure DOM code with JavaScript or jQuery to render content. Or you recall using tools like handlebars or mustache to render content. Or maybe you’ve never rendered to the DOM without a framework. You can imagine what today’s libraries and frameworks are doing under the covers to render content for you.

        It’s helpful to know what can be done with pure HTML, TypeScript/JavaScript, and CSS even if you are using a framework that abstracts this from you.

        Whatever your experience, I hope it was helpful to take a brief exploration through some of the techniques that you can use to render content.

        Source:: johnpapa