Enable full ES6 support in Node.js – dynamic transpiling with Babel

Finally I’ve decided to go beyond Promises with Node.js and started to look how can I write easily ES6 code today in my apps. I’ve had the option to use io.js which has a good ES6 support by default, starting Node.js with the Harmony flag was also an option. However if I wanted as full as possible ES6 support I had to use Babel. There are 2 options here: static compiling and deploy or dynamic compiling when the application is ran. Babel uses cache so only the changed files are recompiled.

First I had to install babel through npm:

npm install babel --save

It is recommended to install babel globally but I wanted to have it in the local packages for easy CI testing.

Then I added this little piece of code on the top of the main app.js which is the file used when the application is started with `node app.js`:

require("babel/register");

One downside is that the main (app.js) file must contain only ES5 code if the Node.js version you are using is not supporting the new syntax. However you can just create one bootstrap.js that registers babel and includes the app.js which then can contain ES6 code(and vice versa: app.js as the main one including bootstrap.js).

I wanted to have the ES6 support in the tests too and because I use grunt, mocha and istanbul I’ve added this configuration to the Gruntfile.js:

mocha_istanbul: {
    src: 'test/server/',
    options: {
        ...
        mochaOptions: ['--compilers=js:babel/register']
    }
}

That way the tests are running with transpiled files and if I have an ES6 syntax there I am good.

I also had to add/change some configuration in .jshintrc which I use in the tests and in my IDE:

“esnext” : true, //this allows ES6 syntax
“predef”: [“-Promise”] //this allows me to use a Promise lib like bluebird instead the default ES6 implementation

I also changed the JavaScript engine in my IDE (Webstorm) from EcmaScript 5.1 to ES6 to make it happy with the new syntax.

After that I started adding some fat arrow functions and the app/tests are working. It’s interesting how the new features sometimes need more than a basic change. For example the fat arrow functions behave different with this and my code for mongoose static functions that was using return this.somefunc() needed to be changed.

If you use istanbul with the configuration above you may notice that the coverage data shows ES5 code with the source map encoded at the bottom of the pages. There’s an unstable branch on istanbul’s GitHub page about source maps which means that we’ll soon have the coverage in ES6 for free! I’ll also be waiting for the Node.js and io.js to be merged and see what works without transpilers.

Exploring ES6: Upgrade to the next version of JavaScript | exploringjs.com

Source: Exploring ES6: Upgrade to the next version of JavaScript

Today I started reading about ES6 more seriously as the standard is ready and one should start using it. As the author describes we can start changing our ES5 code to ES6 incrementally. Personally I am already using Promises and now it’s time to add something new to my current projects and refactor file by file while learning.

Don’t miss another great book from a great author! It’s free!

You-Dont-Know-JS/es6 & beyond at master · getify/You-Dont-Know-JS

You-Dont-Know-JS – A book series on JavaScript. @YDKJS on twitter.

Source: You-Dont-Know-JS/es6 & beyond at master · getify/You-Dont-Know-JS

A book on ES6. Completely free, hosted on GitHub in a Markdown format which means you just click links and read long and smart chapters!

Is ReactJS faster than AngularJS ? | blog.500tech.com

Short answer ? Nope.Long answer ? Inside.

Source: Is ReactJS faster than AngularJS ?

The author said it well:

ReactJS is a great framework which we at 500Tech use and love. There are many benefits to choosing ReactJS for your next project. “Speed” should not be one of them.

It is shown that one must know very well the framework and environment he uses to be able to write code that executes fast. This usually comes with months/years of getting the right experience/reading resources in your day job and while working with other devs as a whole.

Be sure to check the comments as they point the good things in both frameworks.

I personally will stick with Angular, getting ready for version 2 and will continue reading from different sources about it to get to know what makes it good and what makes it fast.

Web Design Degree Center – Choosing Your Javascript Framework | WebDesignDegreeCenter.org

Pick your JavaScript framework: Angular.js, Ember.js or Backbone.js.

They all have pros and cons and they all will do the job. They are constantly developed and even introduce breaking changes in new versions which means developers find the flows and anti-patterns in their frameworks and do it right in the next major version for the good of the language and the developers using the frameworks:
Continue reading

The Final Steps to Mastering JavaScript’s “this” Keyword | sitepoint.com

Completing his look at JavaScript’s ‘this’ keyword, Ivaylo Gerchev examines how to use ‘this’ in callbacks and closures, as well as lexical binding in ES6.

Source: The Final Steps to Mastering JavaScript’s “this” Keyword

This article just got me unprepared as I was thinking I already covered all possible situations where “this” is changed by the context. However today I cemented my knowledge!

An Introduction to Functional JavaScript | sitepoint.com

M. David Green demonstrates how you can start thinking functionally in JavaScript, by refactoring some all-too-common imperative code to a functional style.

Source: An Introduction to Functional JavaScript

The article starts with an old classical way of doing things with JavaScript and the DOM. Things like global variables with generic names!

It is then translated to a more modern OOP that uses the IIFE, the strict directive, constructor function and its prototype.

And then we enter the world of functional JavaScript! I can’t remember well right now but the final solution reminds me of a design pattern.

One additional interesting thing in the examples is how the author uses string concatenation through arrays ([].join()) instead of “str1” + “str2” as this way is proved to be faster probably because the + operator is overloaded to work with multiple variable types or something else – just remember that string concatenation in JavaScript is slow.

There’s one other solution to the same problem in the comments which may be called one-liner and also the type of Clever Programming which happens when the code is short, fast and clever but a bit hard for beginners to read and understand fast. However using regex is a must for experienced developers which makes this solution also good.

Keep reading on the link above.

Converting Mongoose model functions to be Promise and callback friendly simultaneously

I just started using promises in one of my Node.js applications after watching the callback hell in some of the code there.

I was going to use Q but while checking the different options I stumbled upon Bluebird and I liked it.

At some time I checked how Mongoose works with promises and discovered that many functions return a promise and also the queries’ exec() returns a promise too. The Promise in Mongoose is mpromise.

However I decided to stick to a single implementation of Promise for my entire application to have something as a standard and predictable way to use “promisified” functions. And this happened to be Bluebird. It’s huge(features) and I like it!

The first thing to “clean” was a function in one of my Mongoose’s models: User.create() – a custom static function that overrides the default create function. I needed the override to be able to receive custom structured arguments and also to do some changes before the model data is saved. I changed the way I handle the create later by removing it and using pre-hooks instead but this is a good example to show and is like a repeatable template for any other function that is going to be converted the same way.

Let’s see the original Promise-free function:

userSchema.static('create', function (data, cb) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
  });
  return user.save(cb);
});

You can see that User.create() receives a data object literal and executes the callback cb after it’s saved.

An example usage of create will be:

User.create({
  facebookId: '68yc7j9y4f64',
  name: 'Iliyan Trifonov',
  photo:'https://...'
}, function userCreateCb (err, user) {
  if (err) {
    return console.error(err);
  }
  if (!user) {
   return console.error('User not created!');
  }
  console.info('User created successfully!', user);
});

Now let’s make User.create return a promise:

First we promisify the model with:

Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);

and then the create function will look like:

userSchema.static('create', function (data) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
 });
 return user.saveAsync();
});

Now we should handle the resolve and reject:

User.create({
  facebookId: '68yc7j9y4f64',
  name: 'Iliyan Trifonov',
  photo:'https://...'
}).then(function (user) {
  console.info('User created successfully!', user);
}).catch(function (err) {
  console.error('Error creating the user!', err);
});

For now I am experimenting with the then(resolveCb)/catch(errorCb) combination but it can be changed to then(resolveCb, rejectCb) or then(resolveCb)/then(null, rejectCb).

But what about the rest of the code that depends on User.create to use a callback?

Let’s add the callback argument again:

userSchema.static('create', function (data, cb) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
  });
  return user.saveAsync().then(function (user) {
    return cb(null, user);
  }).catch(function (err) {
    return cb(err);
  });
});

And now the create function will work with the legacy code and the new Promises code simultaneously!