Category Archives: JavaScript

Reactive Programming

What is Reactive Programming?

Reactive programming is programming paradigm that works with asynchronous data streams.

Data streams can be created from many things such as:

  • UI Events
  • Http Requests
  • File Systems
  • Array-like objects
  • Memory/Cache

Stream

A sequence of ongoing events ordered in time.

Stream emits a value, error and complete signal.

So we can get the data it emits (any type of data) or we can get errors if something goes wrong

or we can get a signal that notifies when it gets complete.

The image below represents a stream.

reactive programming

Observables:

  • Observables are used to watch these streams and emit functions when a value, error or completed signal is returned.
  • Observables can be subscribed to by an observer.
  • Observables will constantly watch streams and will updated accordingly.
  • We can interact with data streams as any regular array.

Simple examples for creating observable

// From one or multiple values
 Rx.Observable.of('foo', 'bar');

// From array of values
 Rx.Observable.from([1,2,3]);

// From an event
 Rx.Observable.fromEvent(document.querySelector('button'), 'click');

// From a Promise
 Rx.Observable.fromPromise(fetch('/users'));

// From a callback (last argument is a callback)
 // fs.exists = (path, cb(exists))
 var exists = Rx.Observable.bindCallback(fs.exists);
 exists('file.txt').subscribe(exists => console.log('Does file exist?', exists));

Now, we cannot use standard JavaScript ES5 or ES6 to work with Observables and Streams and Reactive Extensions or ReactiveX is what allows us to do that.

Reactive Extension/ReactiveX

  • A library for composing asynchronous programs by using observable sequences.
  • Provides a long list of operators which allow us to filter, select, combine, and compose observables.

Other Implementations of the Reactive Extensions:

Sharing the web Application

If you want to share your work in the public web, so that your client can review the work in progress then you might think of traditional cloud service providers like AWS, Azure, etc.

But, there are a list of services which makes it very easy to share your work in progress without having to configure cloud provider or pay for hosting.

These services are:

  • localtunnel

  • ngrok

  • Surge

  • now

localtunnel

– localtunnel exposes your localhost to the world for easy testing and sharing via public url. It uses your local machine which act as a web server.

Setup :

  • npm install -g localtunnel
    This will install the localtunnel module globally and add the ‘lt’ client cli tool to your PATH.
  • Start your app.
  • Assuming your local server is running on port 3000, just use the lt command to start the tunnel.
  • lt –port 3000

ngrok

– It also uses your local machine as a web server and exposes the local server behind a NAT or firewall to the internet.

As per github documentation, it is a reverse proxy that creates a secure tunnel from a public endpoint to a locally running web service. ngrok captures and analyzes all traffic over the tunnel for later inspection and replay.

It offers some additional features over localtunnel but requires some additional setup to support it.

Ngrok’s advantage over localtunnel is security. You can password protect access. With localtunnel, anyone with the url can access your app while your localtunnel is open. But the advantage of localtunnel is its lower friction to get setup.

Setup:

  • Sign Up
  • Install ngrok
  • Install authtoken
  • Start your app
  • Run ngrok command –

./ngrok http 3000 (assuming your app is running on port 3000)

now

– It allows you to take your JavaScript (Node.js) or Docker powered websites, applications and services to the cloud with ease, speed and reliability.

It takes different approach than localtunnel and ngrok because it doesn’t punch a hole in your firewall instead it is an easy way to deploy your app in the cloud so that the others can review it. Any directory containing package.json can be uploaded to the cloud using one command “now”. Each time you deploy to now, you’re assigned a new unique url.

You can also use now for your production deployment.

Setup:

  • npm install -g now
  • Create start script which opens your preferred web server such as express.
  • To deploy the app, just type > now

Since now publishes files to actual web server, it’s a more permanent solution compared to localtunnel or ngrok. You don’t need to keep your machine on for people to see your work in progress. If you application has a server side component that’s node based then now is a great option.

Surge

– Static web publishing for Front-End Developers. Quickly host static files to public URL.
So the downside of surge is that It only supports static files but the upside is its extreme simplicity.

Surge publishes your static files to their service and serves them at a public url.

Setup:

  • npm install -g surge
  • surge

The first time you run surge, you’ll be promoted to enter an email and password on the command line. Otherwise it will list your existing login and confirm the path that you would like to serve. It will provide you a randomly generated url unless you provide your own custom subdomain by providing a parameter like :

-d, --domain
 domain of your project (.surge.sh)

It will upload your app and expose it on the url listed.

Development Webservers

Some of the web servers to consider for JavaScript development.

 

http-server

It is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it’s simple and hackable enough to be used for testing, local development, and learning.

Its super lightweight and it serves current directory with single command.

 

live-server

It is also lightweight but adds live reloading capability so that every time you hit save, your changes are immediately visible. This is a nice improvement over http-server.

 

express

It is a lightweight web server bundled with a lot of features like

  • Robust routing
  • Focus on high performance
  • Super-high test coverage
  • HTTP helpers (redirection, caching, etc)
  • View system supporting 14+ template engines
  • Content negotiation
  • Executable for generating applications quickly

It is highly configurable. Unlike http-server and live-server, it’s not just for static files.

You can serve complex api via node using express as well.

The advantage of using express in dev server is you can use it in production as well.

This allow you to use common configuration and use it in all environments.

 

budo

It is a web server for rapid prototyping.

  • Integrates with browserify
  • Includes hot reloading (reflect any change to your files without restarting server).

 

webpack-dev-server

  • Built in web server.
  • It’s very fast to reflect changes because it doesn’t require generating any physical files. It serves your app from memory
  • Supports hot reloading.

 

Browsersync

Keep multiple browsers & devices in sync when building websites.

  • Dedicated IP for sharing work on LAN

It sets up dedicated IP address on your local network so that you or anyone that can hit the IP on your LAN can see your app.

  • All interactions remain in sync.
  • Great for cross-device testing
  • Integrates with webpack and express

You can augment your existing web server with additional features using Browsersync.

 

Note: Except express, all the above web servers are only for development environment.

Package Security

Packages can be published in npm by anyone, so that can bring vulnerabilities in packages with it.

Thankfully, there are modules which can help you to check your project dependencies for known vulnerabilities.

These modules are retire.js and Node Security Platform.

Node Security Platform (NSP)

Continuous Security monitoring for your node apps

NSP is more preferable at this time. It provides a simple command line interface so that you can automate check for security vulnerabilities automatically.

You can run command > nsp check during the build and then it reports the number of vulnerabilities found, if any.

There are number of options when to run this and they all have their tradeoffs.

  • The first option is to manually run node security check but that’s easy to forget
  • The second option is run it as part of npm install but the packages you used may have security issues later. So merely check install isn’t sufficient.
  • The third option is to run it during production build or if you are using github, automatically as part of your pull request but both of these options are bit too late because by then you have already used the package.
  • The final option is to check it as part of npm install. This way each time you start development, the security status of you packages are checked. This does have downside of slow start a bit and requiring a network connection to perform the check but it has the advantage of notifying you quickly when a security issue exist.

Setting up Node Security Platform

To perform node security scanning, you can install node security project globally, so that you can run it directly on the command line.

To install globally, Type > npm install -g nsp

Once it is installed, just type > nsp check

It will show the known vulnerabilities for the node modules that you have added.

Retire.js

“Using Components with Known Vulnerabilities” is now a part of the OWASP Top 10 and insecure libraries can pose a huge risk for your webapp. The goal of Retire.js is to help you detect use of version with known vulnerabilities.

Retire.js has these parts:

  • A command line scanner
  • A grunt plugin
  • A Chrome extension
  • A Firefox extension
  • Burp and OWASP Zap plugin

For more details. Visit here Retire JS

Package Management

Every language benefits from a standardized method for sharing code.
JavaScript provides multiple options.

Bower
Bower used to be a very popular option but more people have started moving to npm.
Bower became popular by supporting the entire web platform and packaging libraries in a format that didn’t require build step. Today, nearly everyone has a build step because they are transpiling, minifying, linting and so on.
So bower has become mostly irrelevant.

NPM
It stands for Node Package Manager. Node has grown wildly in popularity and bundlers continue to become powerful. Hence, it has become a de-facto standard for JavaScript package managers. Today, npm is clearly the most popular package manager for JavaScript.

It offers almost everything that you need.

JSPM
It stands for JavaScript package manager. It is frictionless browser package management

  • It allows you to install packages from its own list of repositories as well as from other locations including npm, github and bower. It also bundles your code.
  • For development, load modules as separate files with ES6 and plugins compiled in the browser.
  • For production (or development too), optimize into a bundle, layered bundles or a self-executing bundle with a single command.

There are some other less popular options like

Jam
Jam is a package manager for JavaScript.

It has features like:

  • Manage dependencies
  • Fast and modular
  • Use with existing stack
  • Custom builds
  • Focus on size

Volo
volo is a tool which lets you quickly create projects, add libraries, and automate common tasks using node and JavaScript.

It creates browser-based, front-end projects from project templates, and add dependencies by fetching them from GitHub. Once your project is set up, automate common tasks.

Getting started with Node Package Manager

Creating package.json

To create a package.json run:
npm init

This will initiate a command line questionnaire that will conclude with the creation of a package.json in the directory you initiated the command.

Package.json file contents:

  • name: name of the project
  • version: initial version. Default 1.0.0
  • description: description of project
  • scripts: by default creates a empty test script. It helps to automate processes.
  • keywords: empty
  • author: whatever you provided the CLI
  • license: ISC
  • dependencies – Production dependencies
  • devDependencies – Development Dependencies
  • repository: will pull in info from the current directory, if present
  • bugs: will pull in info from the current directory, if present
  • homepage: will pull in info from the current directory, if present

Sample package.json

{
“name”: “Sample javascript project”,
“version”: “1.0.0”,
“description”: “Sample project in JavaScript”,
“scripts”: {
“start”: “npm start”,
},
“author”: “xyz”,
“license”: “MIT”,
“dependencies”: {
“favicon”: “0.0.2”,
“http”: “0.0.0”,
“jade”: “*”,
“mongojs”: “^2.4.0”,
“path”: “^0.12.7”,
“router”: “^1.1.4”
},
“devDependencies”: {
“babel-cli”: “6.16.0”,
“babel-core”: “6.17.0”,
“babel-loader”: “6.2.5”,
“babel-preset-latest”: “6.16.0”,
“babel-register”: “6.16.3”,
“chai”: “3.5.0”,
“eslint”: “3.8.1”,
“express”: “4.14.0”,
“jsdom”: “9.8.0”,
“localtunnel”: “1.8.1”,
“mocha”: “3.1.2”,
“nock”: “8.1.0”,
“npm-run-all”: “3.1.1”,
“nsp”: “2.6.2”,
“numeral”: “1.5.3”,
“style-loader”: “0.13.1”,
“surge”: “0.18.0”,
“webpack”: “1.13.2”,
“webpack-md5-hash”: “0.0.5”
}
}

To install the above packages:
Go to the path where package.json is present.

Type >npm install (Require internet connection).

Once this is done, you can see a node_modules folder under the same path containing all the above package along with the dependent modules.

What to look for in JavaScript Editors

Strong ES2015+ support

It should offer strong support for latest JavaScript features.

Most editors do so today but keep in mind the larger your editor is, the slower it will typical be to add support for new JavaScript features.

It will also likely to be slower to add support for alternative languages that transpile to JavaScript in future.

Features to look for:

  • Autocompletion
  • Parse ES6 imports
  • Report unused imports
  • Automated refactoring

Many editors now offers build in support for popular frameworks and libraries like Angular, Node, React, etc.

Built in terminal

Tools like WebStorm provides build in terminal. Most of the tools in JavaScript rely on the command line. So it would be good to have it.

Some editors like Atom, allow adding a built-in terminal by installing  a plugin.

Some of the best free editors are:

Atom

Atom is a modern, approachable, and hackable text editor built on top of Electron. It’s designed to be customizable, but also usable without needing to edit a config file.

Download

Brackets

An open source code editor for the web, written in JavaScript, HTML and CSS.

Download

Visual Studio Code

Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and mac OS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring.

Download

Online JavaScript Editors

JS Bin

It allow creating, sharing and editing web client-side including JavaScript, html and css through the community.

jsbin make it easy teamwork development and troubleshooting by making modular working demos of code available for everyone in your team or community.

JSFiddle

JSFiddle is an online Integrated Development Environment (ide) that is hosted in a browser allowing users to create and execute code written in JavaScript, html, and css. It has features enabling users to learn and demonstrate how JavaScript, HTML, and CSS work together, and is often used to provide live examples of problems being encountered.

CodePen

CodePen is an HTML, CSS, and JavaScript code editor in your browser with instant previews of the code you see and write. Very cool platform, and has thousands upon thousands of examples, of how versatile web development can be, and what can be achieved through combining three programming languages.

Rendera

Many new developers and designers underestimate, the amount of time that goes into switching tabs and seeing whether the code works or not. Rendera provides simple functionality so that you can view the results within one single click.

Getting Started with JavaScript Web Development

Choosing the right tools

Boilerplate

Depending upon the library and frameworks you are working with you may have a variety of development templates or boilerplate available for you to use.

You can ask what might be the advantages of selecting an existing boilerplate project instead of building your own.

Well, the benefits of using someone else’s project is you can save time. At least during initial development.

Reasons to choose boilerplate:

  • Save Time – The more time you have to spent time learning how it works, so that you can tweak it as per your needs for less benefits that they supply.
  • Proven – If many people are using the boilerplate, then you can trust that it’s a proven setup that’s likely to be reliable. This doesn’t mean that it does exactly what you want but at least you can trust what it claims to do.
  • Full Featured – They offered a wide variety of full cases that would be very time consuming to handle when started from scratch.

Build your own

There are many benefits of building your own development environment.

  • Freedom to choose – You are free to choose the best and relevant technologies for your needs
  • Perfect fit for your team – You can build a development environment that best fit for your team and technology stack.
  • No unnecessary complexity – Any existing boilerplate projects are likely to contain technologies that you don’t want or need. It could be time consuming and error prone to removing feature or tweaking how they work when it’s a project you’re not familiar with.
  • Understand it – When you build your own development environment, you’ll understand it in details.
  • Easier to change – This makes it easy to fix bugs and tweak the setup as time passes.