How do I use the Angular ngIf Directive?

Angular

Angular logo - ngFor

Angular’s ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.

It’s perfectly fine to use the Angular ngIf directive to hide / show one or more HTML elements. This is the net effect and when used wisely, there is no problem with this usage. But it is important to be aware that Angular’s ngIf directive actually creates a DOM element or destroys it. If you want to actually hide / show elements without destroying them, then the Angular ngClass attribute would be more appropriate.

The thing to keep in mind when considering whether or not to use the Angular ngIf directive is performance. For example, if you have have hundreds of DOM elements, but do not need to show ALL of them when the component initially renders, then the Angular ngIf directive might be better for performance reasons. As you’ll see, the benefit of this is that only tens or a few hundred DOM elements are created at a time. So this means that as your data changes, the creating / destroying of elements is restricted to fewer elements. But if you have a total of tens or perhaps less than 100 DOM elements to manage in your component, then the Anglular ngClass attribute might be a better choice. You’ll find that performance is improved when using the Anglular ngClass attribute because DOM elements will be hidden-shown via CSS, not JavaScript

Example # 1

In Example # 1, we have our component. There is a contentVisible property. It is a boolean, and set to false by default. We will consume the contentVisible property in our template (see Example # 2).

Example # 2

In Example # 2, we have our template. Notice that the div element has an ngIf attribute. This attribute’s value is the result of the contentVisible property. So if the contentVisible property is true, then the div element is created. Conversely, if the contentVisible property is false, then the div element is destroyed. The net effect is that the element is hidden / shown, but it is important to note that the element is actually created / destroyed.

There are two buttons in the template. Each button has a click event handler. In each case, the button sets the value of the contentVisible property. Each button also has an ngIf attribute. Because they both change the value of the contentVisible property, they change the visibility of both buttons. That is to say, when the first button is clicked, it is immediately destroyed and the other button is created, and vice verse.

The main thing to note in this example is that these buttons change the value of the contentVisible property, which seems to hide / show the div. However, the div is actually being created and destroyed.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-ngIf

Summary

So, it’s important to understand that the Angular ngIf directive actually creates and destroys DOM elements. The Angular ngIf directive could be a strong or weak design choice, depending on the context of your component. It’s also a DOM management choice, and whether or not you’re working with hundreds or thousands of DOM elements. So, overall, the approach you take could have a major impact on the performance of your component.

ERROR in [at-loader] Duplicate function implementation

Jasmine

Angular Logo

If your wrap your unit tests in one global function, that function name must be unique across all of your tests

I have some OCD issues. I guess that’s why I like writing code. My OCD tendencies are no less apparent in my unit tests: I tend to wrap all of my tests in a global function.

The main reason for this is: test data.

Test data is a reality of unit tests and something that happens often. But I really hate to see a whole bunch of boilerplate code at the top of a unit test. I don’t want to see all of that, I just want to jump into the tests. So what I do is: I create all of the test data at the bottom of the file. I feel that this makes the unit tests much easier to read.

But since I want all of the test data to be available before the tests run, I wrap all of the tests in a function, create the test data, and then execute the function that contains all of the tests.

Example # 1

In example # 1, I’ve set up a unit test. The test data is at the top of the file, which to me make the test hard to read.

Example # 2:

In example # 2, I wrapped the unit tests in the function: runTests. This way I create the tests, create the test data, and then execute the runTests function. I like this approach because my test data is at the bottom of the file, and the actual unit test is at the top, which I feel makes the code easier to read.

After upgrading to Angular 4 (and subsequently upgrading the npm packages karma & karma-jasmine), I got a whole bunch of instances of this error: ERROR in [at-loader] Duplicate function implementation. I don’t get the error if there is only one unit test, but as soon as I introduce more than one unit-test file, I get the error (and the more files there are, the more errors there are).

This took a bit to figure out, but I finally got it. My runTests function is a global, and Jasmine does not like when there is more than one instance of it declared.

Example # 3:

In example # 3, I renamed the runTests function to runTests_ServiceA. And in each unit test file, I did the same exact thing. For example: runTests_ServiceB, runTests_ServiceC, runTests_ServiceD, etc…

This way, each runTests function  has a unique name. While I don’t always have test data, this is just a pattern I like to follow. The latest versions of the karma & karma-jasmine npm packages did not like the fact that multiple instance of the runTests function  were being declared, so I just make sure that in each unit test file, that function has a unique name. An easy way to do this is to simply append “_ServiceName” to runTests. But as long as the function name is unique, any name will do.

Jasmine – parameter XXX implicitly has an “any” type.

Jasmine

Angular Logo

After upgrading from Angular 2 to Angular 4, Jasmine started to complain about values that did not even exist in my unit tests

I recently posted an article about a Jasmine issue that arose with regards to the globals: describe, beforeEach, expect and it. That turned out to be related to how types are handled in Angular 4.

Once I got that problem straightened out, there were some really odd errors. The thing that was driving me nuts was: the values that Jasmine complained about did not even exist in my unit tests… gggrrrrr.

This is one that could have taken forever. Actually, I did spend at least 30 minutes scratching my head. Fortunately, I found the answer on Github: I needed to make a change to tsconfig.json. In the compilerOptions object, set noImplicitAny to false.

For example:

Credit goes to Zama Khan Mohammed for this answer.

 

Jasmine – Cannot find name describe (or beforeEach, expect and it)

Jasmine

Angular Logo

After upgrading from Angular 2 to Angular 4, there were some delightful new errors in my unit tests

After some initial hair-pulling, I’ve finally got my unit tests working again after upgrading from Angular 2 to Angular 4. But once I started running the tests, I found these lovely errors:

I knew it could not be the unit tests themselves; it had to be something low-level. Then it occurred to me that in my Angular 2 implementation, I had a typings.json file in the root of my application to handle types such as jasmine , lodash and moment. But with Angular 4, types are handled in package.json via the @types namespace.

So, after some searching, I found this Stackoverflow article: Angular 2 Unit Tests: Cannot find name ‘describe’. The solution provided worked perfectly for me.

Two Steps:

1 – In package.json, add this line to your devDependencies:

2 – And then in your unit test file (i.e. XXX.spec.ts), add this line:

All of the errors that complain about describe, beforeEach, expect and it should no longer appear in your terminal.

Major credit goes to ksharifbd for this answer. This was a major time-saver!

Dependency: spring-boot-configuration-processor unknown

Java Spring Boot

JavaScript LogoWhen adding spring-boot-configuration-processor as a dependency, Maven > Reimport is needed

In my Spring Boot project, I was just attempting to add a dependency section to my pom.xml file. The groupId is org.springframework.boot, and the artifactId is spring-boot-configuration-processor. But IntelliJ IDEA highlights spring-boot-configuration-processor in BOLD RED and shows the error: “spring-boot-configuration-processor unknown.” The whole problem started because in my .java file, I was attempting to use the @EnableConfigurationProperties annotation.

A few minutes of searching led me to the page: Maven Repository: org.springframework.boot » spring-boot-configuration-processor » 1.5.4.RELEASE. Since I am using the 1.5.4.RELEASE version of org.springframework.boot.spring-boot-starter-parent, this sure looked like the exact page I needed.

Unfortunately, even with what appeared to be the exact and correct config properties, the BOLD RED highlighting and error persisted.

After some searching I found out that Maven > Reimport is needed. The steps to fix this are simple:

  • Right-click your project
  • Click Maven
  • Click Reimport

The above screenshot shows the menu. After a Reimport, the BOLD RED highlighting and error went away. The article Spring Boot Support in Spring Tool Suite 3.6.4 references Spring Tools Suite, but the content of the post led me in the right direction towards solving the problem. Scroll down to where you see the text: “Add this to the pom.xml”. That section might be helpful to you. But instead of Maven >> Update Project it’s Maven >> Reimport.

The Apache Tomcat installation at this directory is version 8.5.15 Tomcat 8.0 installation is expected

Java

The Paradox of JavaScript

The problem is in ServerInfo.properties

I was just attempting to add an Apache Tomcat server to Eclipse Java EE IDE for Web Developers, Version: Mars.2, when I ran into a nasty snag: In the New Server dialog, the Next> button is not enabled. I also noticed an error in the top of the dialog: “The Apache Tomcat installation at this directory is version 8.5.15. A Tomcat 8.0 installation is expected“. Very annoying.

After some searching I found out that the problem is in ServerInfo.properties. The server.info= line needs to have the value: Apache Tomcat/8.0.0.

The Apache Tomcat installation at this directory is version 8.5.15 Tomcat 8.0 installation is expected

The above screenshot shows the issue. So if you run into this problem, this Stack Overflow article:  How to use Tomcat 8.5.x and TomEE 7.x with Eclipse? – Stack Overflow has the answer you need. Check out the answer by dexter-meyers. But also note the edit by informatik01. In short, you want to follow the detailed steps to patch catalina.jar, but you only need to change the version in the server.info= line.

For the complete answer to this issue, check out this Stack Overflow page:

https://stackoverflow.com/questions/37024876/how-to-use-tomcat-8-5-x-and-tomee-7-x-with-eclipse

 

 

The Paradox of JavaScript

JavaScript

JavaScript LogoAre you getting an ECMA-Headache?

In the book: The Paradox of Choice: Why More Is Less, author Barry Schwartz argues that too many choices can dilute satisfaction. While this title spends much of its time in the context of consumer products, a similar argument can be made about the world of JavaScript. There is so much going on in the wild wild west that is JS, but is that really a good thing?

In short, I’d say  yes, it is a good thing. Even though it can be difficult to navigate the maze of libraries and frameworks, the explosion of activity breeds a world of innovation and creativity. But there is no doubt a cost; Where to begin? How to keep up? There is a lot of noise associated with the world of JavaScript. I actually feel that most of it is good noise, but it can be overwhelming.

I recently participated in an  Aquent Gymnasium webinar titled: keeping up with javascript is a full-time job, and I thought the title was brilliant. Not only are beginners feeling JavaScript anxiety, but experienced developers as well. I’ve heard many people ask the same questions: “Should I learn Angular or React”? – “If few ES-2015 features are currently supported, should I still learn them?” – “Grunt , Gulp or Webpack?” and so on.

ES6 vs ES-2015 vs ES-2016 vs ES-WTF

And speaking of ECMAScript, what is up with the naming-scheme? ES6 is AKA ES-2015, and ES7 is AKA 2016? Ok, that’s easy to remember. But what to learn? What the hell is a JavaScript symbol? And, what significance does it play in the million-and-fifty-fifth JavaScript slideshow I will have to make in my next Agile Sprint? Is this just like all that cruddy math that we had to learn in 8th grade, knowing perfectly well that we’d never ever need it in adult life?

Sigh.

So many libraries, so little time

This is where the paradox may lie. We have so many JavaScript toys to play with, but who has time to keep up with all of them? First, you have to be aware of changes in the JavaScript jungle. For example, Angular 4 is out, but there is no Angular3. Okie dokie. Next you have to understand the role of each library or framework. And then at some point, you want to learn how to use it, right?

Sometimes it is really tough to know where to invest your time. I’ve been hearing more and more about Aurelia and Vue.js. Both have enjoyed positive reviews and are gaining traction. But are they really going to take off line Angular? Am I really going to benefit in my next job interview by learning either one of these libraries or any of the other up-and-coming JavaScript libraries/frameworks ?

My answer: Bet on JavaScript every time

I’m not sure it is necessary to learn every single JavaScript framework or library that falls from the tree. We all have lives to live and there are only 24 hours in each day.

Something interesting about all of this craziness is that there is one common thread throughout: JavaScript.  JavaScript is the language used in all of these libraries/frameworks/build tools. So, you simply cannot lose by making JavaScript your top priority. If you have a free hour, spend 45 minutes studying JavaScript, and 15-minutes learning a new library. As long as your JavaScript skills continue to improve, you will always have the tools you need to learn any new library/framework/build tool. Not only that, but you will get better at picking them up. In addition, you will start to see the similarities between them and common patterns in the source code.

In short: you simply cannot lose by concentrating on JavaScript.

ECMA-Everything

Not only is it important to focus on JavaScript, but it is also key to learn the new features of the specification.  Most browsers do not support these features, but they will soon, so best to get ahead of the eight-ball. ES-6 and ES-7 features are powerful and when supported, will take much of the pain out of creating sophisticated client-side web applications. More important than Angular, more important than React, learn the newest features of JavaScript. And, Babel is your friend; it allows you to use features that browsers do not yet support. Also, the combination of Typescript/Webpack is another solid solution.

Planning is key

I can only speak to what has worked for me, and that is: always trying to decide where my time is best spent. For example, one of the biggest arguments in the JavaScript world is: “should I learn Angular or React?” Well, I’d say: learn both!

You don’t have to master each one, but learn enough to understand the differences between them as well as their strengths / weaknesses. Since, I happen to spend 90% of my professional day working with Angular2, I am a fan. But, I was worried that I was falling behind on my knowledge of React, so I spent my last Christmas holiday building an application with React. Now, I am far from a React guru, but in building a simple CRUD application that I actually use each day, I was able to gain an understanding of how it works, how it differs from Angular, and what its strengths are.

I’ve tried to take this approach with every other segment of the JavaScript ecosystem: NPM vs Yarn, Gulp vs Grunt vs Webpack, Typescript vs Vanilla JavaScript, and so on. In each case I ask myself: “What is the most important thing I need to know about this library/framework/build-tool ?” and then my goal is to be able to speak intelligently about it. Sometimes it takes a Saturday afternoon, sometimes it takes a month. Sometimes it turns out that I wind up using that particular tool heavily in my daily work. But I try to at least understand what it does, how it differs from its competitor and what it brings to the table.

Summary

In my opinion, there will always be a couple of JavaScript libraries or frameworks that you work with on a daily basis, a few that you used to work with, and then a zillion that you have heard of but have not had time to learn yet. They key from my perspective, is to accept this reality; you can’t have an expert-level knowledge of everything. But you can keep your finger on the pulse of what’s going on out there, and do your best to have a good understanding of the more popular tools and the role the play.

Why the create-react-app Node module is so awesome

React

angular2 KEYWORD

This tool is perfect for beginners as well as React experts

The JavaScript ecosystem is the wild wild west of the technology world. It seems like every year there is a new heavyweight champ. Right now, Angular and React are duking it out for the belt. They are both solid and enjoy tremendous corporate backing / community support. But they are as different as chalk and cheese. Learning new technologies can be painful. Chances are you got here because you have decided to take the dive into the world of React. Depending on your level of experience, this can be a challenge. The create-react-app Node module can definitely help.

Abstraction

The create-react-app Node module protects you from all of the pain involved with setting-up a React application. Granted, there are tons of JSFiddle links out there that show you how you can spin-up a React application simply by adding to script tags to your web page. Yes, but this kins of setup is not going to cut it in the real world. These are examples that help you get up-and-running and learn.

If you are going to build a real production-ready React application, even a small one, you need some kind of workflow. This is where the pain is: front-end tooling. The create-react-app Node module takes care of all of that for you, literally. Once you have cloned the github repo, you simply execute the following command: create-react-app YOUR_APP_NAME.

Yep, that’s it!

The create-react-app  module takes care of all your Webpack, Babel & ESLint configuration and setup. The funny thing is: you don’t see it. Under the hood there is one main dependency: the react-scripts Node module. This module is like your personal front-end engineer. It sets-up Webpack and Babel  and configures it. You never have to write one line of configuration code for any of this. After you run that create-react-app YOUR_APP_NAME command,  you cd YOUR_APP_NAME, and the npm install. After the npm install is complete, npm start is your last terminal command and your local instance is alive in the browser.

Why this is so amazing

The beauty of all this is: you can get a production-ready React application setup in about 3 minutes. Not only that, this setup was created by the Facebook React team and sanctioned by them. So, you have a great template to start with. The actual application itself is literally a static “Hello World” HTML page. Before you complain, keep in mind that if you are going to learn React, you have to actually write a little code! But the really amazing part is that the most painful aspect of setting up a React application is taken care of for you. You can clone, create, install in a couple of minutes and then start writing code.

Ejecting

Finally, there is the “Eject” command. When you run npm run eject, the create-react-app Node module will un-wrap all of the abstraction. What this means is: all of the front-end tooling remains in-tact and continues to work perfectly, but you are no longer protected from it. Tools such as Webpack and Babel are now available to you and completely customizable. The advantage to this approach is that you can customize your application however you like. It’s also a great way to learn about front-end tooling: you can really see the recommended ways that these tools are configured.

Down sides

There are a few downsides to the create-react-app Node module. The biggest one is that there is no consideration for CSS pre-processors such as LESS and SASS. Also, you cannot configure your application when creating it. You are stuck with the configuration and tooling that is provided. Of course you can use the eject command to reveal all of that detail and do as you wish, but that brings us to the final downside: when you eject, you can never go back.

Gettin’ Down with BaconIpsum

JSON

angular2 baconipsum json

Sometimes you need Lorem Ipsum, and sometimes you need it in json format via an API call. If you don’t mind bacon references spattered throughout that latin, then Bacon Ipsum can help.

I’ve already written an article about the need to make an API call before that service is ready. And myjson.com is a perfect tool for that. But if you just need a lot of text and want to generate it via an API, then Bacon Ipsum is a fun tool that can solve that problem.

The overall concept is a bit silly. I mean, lorem ipsum is kind of silly, and having words like  “bacon”, “flank” and “shankle” sprinkled throughout borders on nonsense. But their API works well and is very easy to use. So, if you are in the middle of a dev project and need some dummy text in JSON format, it’s nifty stuff.

Json API

The landing page allows you to generate some Bacon Ipsum on the fly, but if you want the API calls, then go to baconipsum.com/json-api. There  you’ve got very simple instructions on how to get your Bacon using simple query string parameters. These parameters allows you to control how many words and paragraphs will be returned.

Other Bacon-stuff

If you find this all funny and want more Bacon, they also offer a Chrome extension as well as Android and IOS apps that allow you to… well, I’m sure you can figure out what these do… more Bacon. Although I will note that these apps are pretty outdated, so use at your own risk. There is a jQuery plugin, and three.. count ’em three WordPress plugins for increased Bacon madness. And to top it all off: a baconmockup HTML generator. This might be a bit too much Bacon for me. They had me at the JSON API calls.

Angular2 HTTP Observables in Five Minutes

Angular 2

rxis angular2 observablesObservables are the way to stream data in Angular2. Here’s how to get it working.

Managing asynchronous activities in any JavaScript-driven application can be tricky. Every framework / library has an approach, and there are proven design patterns that are worth considering. In Angular 1.x, $q is the engine that drives this. In Angular 2, it’s RxJS. This technology is not for the faint at heart. It’s very cool, and works well, but does take some getting used to.

This article has one focus: providing example code that demonstrates how to create an observable, and then consume it. So you can start out by cloning the Github repository below. Once you’ve done that, you can run the example code locally and see it in action.

https://github.com/kevinchisholm/angular2-http-observables-in-five-minutes

 

Making the HTTP request

In the following example, we will make an HTTP request, and then stream the return data to anyone who has subscribed to it.

Example # 1

In Example # 1, we have the code for the PackageService service. This service makes the HTTP request for the JSON data. I’m using myjson.com so that we don’t have to spend time with implementation details about serving up the JSON. We just want to make the request and then talk about how we can share that data across our application via an RXJS stream.

So let’s talk about this line:

Here we create the packageData property.  Although it will be an array, it will be a BehaviorSubject instance. So when we define the property, we specify that it is of type: Subject. Then we instantiate the BehaviorSubject class, passing it an empty array. The reason for the empty array is that we don’t want to stream “undefined. Somewhere else in our code, there is a consumer who will want to subscribe to this stream. That consumer expects an array. It’s fine if the array is empty at first. We just don’t want the consumer to get “undefined“.

Later in Example # 1, we call the http.get method. We map that result to JSON, and then we subscribe to that JSON. I don’t want to get into too many implementation details about the last sentence, as I promised that this would take “five minutes.” So let’s focus on the next line: subscribe. By subscribing to this JSON, we are saying “Hey, any time there is  a change in this JSON, I want to know about it.” And when that change occurs, then the function you see passed to the subscribe method is executed.

That function will receive the updated JSON data as its first argument. The very next line is critical: this.packageData.next(data). What’s happening here is: the packageData object that we created earlier has a “next” method. That method takes an argument, which can be anything. In our case, it is the JSON data. So, anyone who has subscribed to our packageData property will receive a notification that there is new data and will be passed that data.

Example # 2

In Example # 2, we have our PackagesComponent component. So let’s zero-in on the critical part: the ngOnInit method. Well, as you probably guessed by the name, this method is executed when our component is initialized. Take a look at this line: this.packageService .packageData .subscribe. There we are subscribing to the packageData property that we created in the packageService service. Because that is an instance of BehaviorSubject, subscribing to it gives us a live connection to anything it streams out. In our case, the http.get request fetched some JSON data. And in that service, the JSON data is streamed out via the  line: this.packageData.next(data). The JSON data comes to the subscribe callback via the variable: “packages.” So we set this.destinations = packages. Therefore, at that point, the UI is updated and we see the list of travel packages in the page.

Summary

I promised that this would take less than five minutes. Hopefully, it did. RXJS is a deep subject that takes some time to get familiar with. I wrote this article because the first time I needed to stream the result of an HTTP request in an Angular2 application, it was a giant pain in the rump.  But here, I have tried to provide an easy example of how to sketch out this scenario and get it working quickly. I hope it was helpful!

Set up a Node / Express Static Web Server in Five Minutes

Node.js

node express static web server

Setting up Node and Express as a Simple Lightweight Web Server for Your Single Page Application is Very Easy to Do.

Sometimes you just need a local web server.  Sure, you could use MAMP, but installing Apache, MySQL and PHP seems like overkill in some cases. I have used MAMP for years and it is terrific. In particular, when you need to run PHP locally and / or connect to a MySQL database, it’s the cats pajamas. But that was the standard 10 years ago. Nowadays, it’s very common to build a single page web application where all of the assets are static, data is pulled-in from a REST endpoint and all of the heavy lifting is done in the browser via JavaScript. In these kinds of scenarios, a static Node / Express server is a simple, easy and lightweight approach.

In this article I’ll explain the steps needed to set up a Node / Express Static Web Server. And the good news is that on this high level, the required steps are very simple. First, you’ll need to require the express and path modules. After that, you’ll create an instance of express, then set the port that the web-server will use. The next step, and the key-ingredient here is the express.static method. This tells Express.js that you want to serve static content from a specific folder. In that one line of code, you’ve done the majority of the configuration work.

So, not only will Express serve-up static content from that folder, it can do so for any subfolders as well. You can specify any folder in your project as the static web folder. And the beauty of it is that any folder outside of the one you specify will be hidden from public view, so your application code will be safe. When you pass the the express.static method to the use method of your express instance, you provide the details that express needs to serve your static content. Then finally, you use the listen method of your express instance to start the web server. We’ll take a closer look at the express.static method in Example # 2.

Now, I just want to remind you here that this article pertains to the specific occasions in which you need to serve static web assets locally. In other words, using a Node / Express static web server can be a very simple way to satisfy your need for a local web server, but may not be the best approach for your production needs. Technically, you could take the code that is detailed in this article and deploy it to your production server, and in theory it would work just fine. For this article, however, I’m just going to concentrate on providing a fast and simple way to get a local web server running so that you can test your front-end code (e.g. HTML, CSS or JavaScript).

The code samples can be downloaded here: https://github.com/kevinchisholm/node-express-static-web-server

Example # 1 – package.json

In Example # 1, we have the contents of package.json. Nothing too special going on here. But just note that our only dependency is the express module. Also, in the scripts property, I’ve set up the start command to execute the app.js file in the node web-server folder. This way, we can simply type npm start in the terminal, instead of node web-server/app.js (just a bit less typing).

Example # 2 – The Express Static Web Server

In Example # 2, we have the entire contents of our web server: 15 lines of code (and nearly 25% of that is comments!). The magic happens on line # 10:  We call the app.use method and pass it express.static, which also takes a couple of arguments. So this tells Express that we want to set a static folder. We then use the path.join method to tell Express where all static assets should be served from. In our case, it is the www folder. The two arguments passed to the path.join method are __dirname, which tells us the absolute path to the folder within which the current script is found, and then “../www” which is a relative path to the www folder.

Now, as I mentioned earlier, anything outside of your static folder is protected from public view. This means that while the folder you specify when calling the express.static() method (i.e. “../www”) is publically viewable, any folder that is a sibling or descendant of that folder is not available publically. This is not a critical factor when working locally (i.e, developing), but it does matter in production. In other words, you wouldn’t want your application code to be viewable to the general public. Nor would you want to make available any sensitive information that’s in your application code, such as a secret key or other credentials. So, as you can see, this is one of the key strengths of Express, which is the ability that it provides you to not only define your public/static folder in one line of code, but to also protect all of the other folders by default.

Express does all of the heavy lifting

A little earlier, I used the word magic. We both know that none of this is actually magic, but it sure feels like it. If you’ve ever created a Node web server manually, then you know two things: 1) It’s really easy, 2) It’s really tedious once you get past “Hello World”.  But Express hides all the tedium and makes serving static assets as easy as 1-2-3.

HTTP Headers

There is one downside here. Express does not set the appropriate content-type headers for the HTTP requests.  This is not fatal in most cases because this approach is simply meant to provide a very fast and easy way to set up a static web server. The actual web server works just fine, but keep in mind that content-type headers for files such as JPEG, PNG, CSS or JS will not be set accordingly. If that is a problem, then a simple static web server is probably not what you need and you should consider a more robust approach. So, hopefully, if you do need a simple static web server, this article was what you needed to get up and running quickly.

Summary

There are multiple options when it comes to setting up a static web server. One advantage to leveraging Node and Express.js, however, is that as a developer, you probably already have Node installed on your machine. So, in this case, you won’t need to install any additional software. You can simply import the Express framework, write about a dozen lines of code, and you have a static web server. This is probably not a server that you would use in production, but as you can see, it can easily solve the problem of quickly serving web content on your local machine. If you need to write moderately complex dynamic application logic, then you might need something a bit more advanced than what was discussed here. But for a basic static web server, this approach should get you going (hopefully in less than five minutes : – )

Getting started with the Cloud9 development environment

Web Development

cloud9 logoIf you are learning web development, Cloud9 offers free and low-cost cloud based environment that provides everything you need to get started.

Every now and then, I’m impressed. I’m not sure how I’ve never heard of this before, but Cloud9 is pretty amazing. This online integrated development environment supports the following languages: C#, C/C++, Clojure, CoffeeScript, ColdFusion, CSS, Groovy, Java, JavaScript, LaTeX, Lua, Markdown, OCaml, PHP, Perl, PowerShell, Python, Ruby, Scala, SCSS, SQL, Textile, X(HTML), XML.  When creating a new project, you can import code from Git, GitHub, Bitbucket or Mercurial.  You can also deploy your projects to Heroku, Joyent, Openshift, Windows Azure, or Google App Engine.

ASS-KICKING WEB-BASED EDITOR

What amazed me right away about Cloud9 is the fact that it is 100% browser-based. There is no software to install or anything to download. You simply fire-up your browser and get to work. In your browser, you’ll find an IDE, as well as a console window. You can chose from a number of editor themes, so you can do for the “Monokai” look if that is your thing.

cloud9 IDE
Cloud9 IDE

Impressive TemPlates

Creating a new application could not be more simple; you can chose from one of about a dozen templates. These include basic HTML5, Node, Python, C++, PHP/Apache, django, Ruby, WordPress, or a blank Ubuntu Linux image. There is even a template specifically for Harvard’s infamous CS50 course.

DATABASE TOO!

Yep. You can configure a database for your application. Cloud9 supports MongoDB, MySQL, CouchDB or Cassandra.  In each case, the setup is slightly more involved than a simple click or two, but overall it’s not too complicated.

Pricing

It’s very cool that they have a free tier. Not only can you kick the tires, but for students, it’s a no-brainer.  You get one private workspace, and then the rest are public. The “Individual” plan is $19 per month. This is not a bad deal at all as you get three “Hot Workspaces” (i.e. they don’t spin-down due to inactivity), unlimited private workspaces, and increased performance. There is a “Teams” plan which is even more robust as well. If you are a full-time student or represent a school, look into their “Education” plan, which will run you a whopping $1 per month. Amazing.

Summary

While services like Heroku, Cloud Foundry, Dokku, Deis, Flynn all make it easy to spin-up various kinds of web-based stacks, Cloud9 makes it even easier. One of the really key aspects of this is the 100% online approach. You do everything in the browser; create files, edit files, deploy your code, even run terminal commands. For serious / production PAAS, I’d go with AWS, but for learning, quick testing, or prototyping, I highly recommend taking a look at Cloud9.

Yikes! AWS Node / NPM ERR! enoent ENOENT: no such file or directory package.json

Node.js

Node.js LogoAWS’s Node deployment keeps telling me that it cannot find package.json, but it’s there! – Fortunately, this problem is easily solved.

AWS makes deploying your Elastic Beanstalk easy. Compress your build files, upload the ZIP and then deploy that application version. Lovely. But sometimes your application goes into a “warning” or “degraded” state, and then a visit to the application with a browser yields: “502 Bad Gateway“. Errrggggg…..

At this point, you look in the logs and see a cryptic message that says something like: “enoent ENOENT: no such file or directory package.json“. You double-triple-quadruple-check and yes, package.json is in-fact very much alive and well. So, of course your next thought it: “WTF???

I have run into this problem a few times and in each case, the problem was me: I zipped-up a folder, instead of the contents of a folder.

Do not compress an entire folder

Compressing the my project folder does not fix package.json problem

Let’s say your Node application is in a folder named: “myProject“. If you are compressing that folder, then this is your problem. You don’t want to compress a folder because when AWS un-zips that file, it will not know to look in the “myProject” folder that is created when the file is un-zipped.

Compress ALL of the items in  your project folder

Compressing the root files fixes package.json problem

What you want to do is: select EVERY file in the root of that folder (i.e. your Node application’s root folder), and then compress THOSE files. This will create a ZIP file that when un-zipped, creates the file structure that AWS expects. Now AWS will find package.json. This should solve the problem.

Compressing the root files fixes package.json problem

In the image above, I have zipped up the contents of the “myProject” folder, and created Archive.zip.

Upload the zipped file

Compressing the root files fixes package.json problem

Now, back in your AWS console, you can use the “Upload and Deploy” button to upload your ZIP file, and then deploy it.

Setting Your AWS-Hosted Node Application’s Port

Node.js

Node.js LogoWhen working locally, using an arbitrary port number is fine, but you need to get that property when deploying your Node application to AWS.

Technically, you can code-up a Node web server in less than ten lines of code. Most likely, your application will require a few more lines of code than that. But my point here is: getting a basic Node web server running is not terribly difficult.

Example # 1

In example # 1, I used port # 3000, but I could have used virtually any valid port number. When working locally this is for the most part a non-issue. As long as no other application is using the port you want to use, you chose one and then use it. Easy. This example does little more than say “Hello!”, but the point I’m trying to make is that your main JS file ends with the server.listen method, and you need to pass it a port number.

But when you attempt to deploy this code to your AWS Elastic Beanstalk instance, you will get a “503 Bad Gateway” error in your browser. The reason for this is: you don’t know which port should be used when calling the server.listen method. The great thing about AWS is that it provides a layer of abstraction for those kinds of details. In other words; AWS takes care of details such as which port to listen on. The downside here is that you have no way of knowing exactly which port that will be when you deploy your code.

Example # 2

In example # 2, we set a variable named: port. We attempt to assign the value of process.env.PORT to that variable. If that value is falsely, then we set it to 3000. The reason this works is; if our code is running on our AWS instance, then process.env.PORT will automatically be set and we will listen on that port. If we are running our code locally, then process.env.PORT will be undefined (or “falsely”). So, then our port variable will have a value of 300. This way, our code can run successfully on our AWS instance, or locally.

Node.js Hosting Links

Node.js

JavaScript LogoThe good news is: there are a lot of Node hosting services out there. The bad news is: there are a lot of Node hosting services out there

Installing Node locally is easy. Cloning an existing Node application from GitHub and running it locally is easy. Creating your own Node application and running it locally is easy. But, choosing a hosting solution for your Node application is definitely not easy.

Below is a list of companies that offer Node hosting services. I do not claim to have every possible company listed here. But I’ve done my best to list the ones that I know about and will update this page any time I learn about another one worth mentioning.


Title: Openshift

Link: openshift.com

Description: I’ve used Openshift.com quite a bit and for the most part have been very happy with their service. They offer a free plan that definitely includes what you need to get up-and-running.


Title: Heroku

Link: heroku.com

Description: Heroku was the first Node hosting service I knew about. I’ve not used it in a while but I was always very happy with it. Setup and deployment was fairly pain-free, as was adding services such as MongoDB.


Title: Amazon Web Services

Link: Deploying Node.js Applications to AWS Elastic Beanstalk

Description: AWS is a big topic. But in general, it’s really easy to get a Node instance up-and-running with Elastic Beanstalk.


Title: Nodejitsu

Link: nodejitsu.com

Description: I’ve not tried Nodejitsu but have heard good things about them.


Title: zeit.co

Link: zeit.co/now

Description: This is a new one to me, but their setup looks super-simple.


Title: Node.js on Google Cloud Platform

Link: cloud.google.com/nodejs

Description: Although Google still has not caught up with Amazon yet, they are serious about their cloud offerings. I’ve not tried their Node hosting but have confidence that it is at worst, solid.


Title: Node.js Hosting

Link: a2hosting.com/nodejs-hosting

Description: Another new one to me, but their packages look very affordable.


Title: Node.js One Click Install | Cloud Hosting – GoDaddy

Link: a2hosting.com/nodejs-hosting

Description: Godaddy now offers a “Cloud” service that supports Node hosting.

Helpful Node.js Education Links

Node.js

JavaScript LogoNode.js is growing fast. This is a great problem. While is means that JavaScript lovers have a rosy future, it can sometimes be difficult to keep up with what is going on with Nodes.js

Here are a list of links that you might find helpful in your Node.js travels. In each case, I’ve provided a brief description of the link / organization / article, so that you have a sense of where you are are headed. If you feel that there is a Node.js link that I should have included in this article, please contact me at: kevin@kevinchisholm.com.

Critical Node.js Links


Node.js Logo

Title: nodejs.org

Link: nodejs.org

Description: Since this is the home page for Node.js, you cannot go wrong here.


Node.js Logo

Title: Node.js v6.6.0 Documentation

Link: nodejs.org/api

Description:The official documentation for Node.js. Very well organized and easy to read. Almost the most important Node.js documentation you can read if you are getting started.


Node.js Logo
Title: npm – Home of the package manager for JavaScript.

Link: www.npmjs.com

Description: It’s hard to imagine doing anything with node without the use of NPM. This is the official home page of NPM, and a great starting point.


Node.js Logo

Title: Homebrew. The better way to install Node.js on Mac OSX

Link: brew.sh

Description: I’m being a little opinionated here (ok. I’m being a lot opinionated). But, for Mac users, Homebrew is the way to go when you install Node.js (sorry Windows users, you are stuck with scoop : – )


Node.js Logo

Title: Built in Node.js – startups, apps, projects using Node

Link: builtinnode.com

Description: A great way to learn about who is using Node.


Node.js Newsletters

Node.js Logo

Title: npm Weekly

Link: www.npmjs.com/npm-weekly

Description: Find out what npm has been working on, thinking about, and talking about every week. A great newsletter if you are into NPM.


Node.js Logo

Title: node weekly

Link: nodeweekly.com

Description: A free, once–weekly e-mail round-up of Node.js news and articles. Another awesome newsletter if you are into Node.


Other Helpful Node.js Links

Node.js Logo

Title: Node Tutorials on scotch.io

Link: scotch.io/tag/node-js

Description: scotch.io tutorials are very easy to read. The site is in general a great resource for learning about a number of web development technologies. Fortunately, they are passionate about Node!

Setting AWS-Node.js Stormpath keys

Node.js

Stormpath Logoprocess.env can be used to set the environment variables you need when using the stormpath api in your aws-hosted node application

Stormpath provides amazing abstraction when it comes to authentication. There are certainly other services like this, but when it comes to security, Stormpath is not only popular, but well respected. This comes as no surprise as they simply make authentication easy.

I have to say that their documentation is for the most part very good. If Node is  your thing, they make it very easy to get up-and-running with their API. Their mailing list is also quite helpful.  At least a once or twice per week, I receive emails that link to interesting articles on their blog.

Recently, I was trying to setup a Node.js/Express.js application, leveraging their express-stormpath Node module. I was thinking to myself: “…hmmmm. There must be a step where I have to configure my secret key or something like that”. After some quality time with Google, I came across this article, that suggested the following:

Unix/Linux/Mac:

Windows:

(where “xxx” is your actual key)

Well, that is fine for working locally, but I knew if I wanted to deploy this as an AWS Elastic Beanstalk application, I needed to actually set these values somewhere.

Using process.env

I set the three environment variables I needed to be properties of process.env:
I

(where “XXX” is your actual key)

I took a look in the source code for the express-stormpath Node module and could see that it seemed to want to find these on process.env, so I think this approach should be fine. I’m still in the process of getting this Node.js/Express.js application up and running, but if you are faced with the same challenge, hopefully this helped you.

MyJson – An awesome tool for mock API calls

JSON

MyJson LogoSometimes you need to call an API that is not ready yet

So you are working on your front-end code. You have crafted you JavaScript so that it is clever and optimized. Check. You’ve created your “makeHttpRequest” method, and configured a success callback. Check. But there is one problem: the back-end team has not completed the API call that you have to make. Rats.

Sure, you can just create some static “dummy” data. But that is not the same thing as an HTTP request, and your code will not be asynchronous. Ok, so you could wrap your static data assignment in a setTimeout. Yeah, that’s it…. nah, just not the same thing as making a real HTTP request. Double rats.

myjson.com saves the day on this one.

This site is so dammed cool, I can’t get over it. You simply add some valid JSON into the large text area, and then click the “Save” button. You are then taken to a page that shows you two things: your JSON and a URL that you can use to make an HTTP request for your JSON. In other words, you just created your very own API call that returns the exact JSON that you need. Sorry folks, this one is better than the Beatles.

At first I was wondering: “…wait a minute. How can I make an HTTP request like this when myjson.com can not possibly have added my silly little test domain to their whitelist for the CORS header?” (yes, I actually talk to myself like this. it’s kind of scary). Well, after about five seconds in the network panel, I see “Access-Control-Allow-Origin: *” . Nice.

Examples:

I literally cannot even begin to imagine the countless hours this would have saved me in the past. Yeah, sure you can spin up something like this on your own, but good gosh; copy, paste, API! how much easier could this be.

Serious Kudos to whoever is behind this.

 

 

 

Angular 2 rc4 Upgrade Links

Angular

Angular Logo

Upgrading from Angular beta to Angular RC is a little painful, and things are going to break. I’ve put together some links that helped reduce some of that pain for me.

A few weeks ago, I had the pleasure of upgrading a client’s singe page application from Angular 2.0.0-beta.12 to Angular 2.0.0-rc.4. As soon as I updated package.json, it broke. I was not surprised, I figured this would happen. Unfortunately, there were more than a few things to fix. Fortunately, the fixes fell into three categories:. 1) The Angular namespace changed. 2) The router changed. 3) Unit tests had to be changed.

None of this was fun, but I got through it. The hardest part was the lack of documentation. I found plenty of out-dated articles with tons of information that was useless to me. Awesome. But the official documentation was minimal to none. And what I found was either tedious  or virtually useless. C’mon ng-folks, you can do better than that.

Here are some links that did provide helpful content for this upgrade:


angular/CHANGELOG.md at master · angular/angular

https://github.com/angular/angular/blob/master/CHANGELOG.md

Details: Essential information for each version release. I can’t imagine living without this. In particular, you can find out about namespace changes.


Forms Upcoming Change Proposal

https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub

Details: Explains the thought-process behind their change to forms. At the very bottom of the article is critical information about how to opt-in to the deprecated forms, or use the new forms module.


Issues after Migration to RC4 in angular2 – Stack Overflow

http://stackoverflow.com/questions/38154399/issues-after-migration-to-rc4-in-angular2

Details: Some helpful information on breaking changes.


Routing & Navigation – ts

https://angular.io/docs/ts/latest/guide/router.html

Details: A very detailed explanation of how the new router works. A long read, but also one of the few thorough their documentation pages.


Defining Child Routes · Rangle.io : Angular 2 Training

http://angular-2-training-book.rangle.io/handout/routing/child_routes.html

Details: Another very detailed explanation of how the new router works.


Plunker

https://plnkr.co/edit/6Mdn7qUblMtktpQyFJAc?p=preview

Details: This plunker is very helpful if you need a quick-and-dirty working example of how child routes work in the new router.