ECMAScript 6 and 7 support in Node.js console through Babel.js

Marco Minetti | Sep 08, 2015

nodejs javascript ecmascript6 ecmascript7 babeljs backport compiler console
Article Goal

This article explains how to get practiced with the latest ECMAScript 6 standard and other experimental features through an enhanced Javascript console. You will get the tools, some tips about experimenting within a console and some useful links to learn ECMAScript 6 and 7.

The next generation of Javascript is right here, right now

The ECMAScript, a.k.a. the official Javascript specification, has been recently and significantly updated after 6 years of just adoption and performance optimization from engine implementers (Chrome, Node.js, Firefox projects and so on).

The new shining version is the ECMAScript 6 or 2015 (because of the standard ratified in June 2015) introduces major features that take Javascript language and developers to the higher level.

The latest features make Javascript much more powerful and effective in the syntax: reducing the gap with, let me say, "professional" and structured languages, such as C# and Java.

But, as the time of writing, the ECMAScript 6 support is not yet completely ready in every platforms. If you're yearning to try having fun with new features, the amazing amazing Babel.js project let you "use next generation Javascript today".

For your convenience, both you're a beginner that just want to friendly practice and you're a professional that is already adopting Babel.js in best-of-breed projects, I have integrated the ECMAScript 6 and 7 support within Node.js console module.

  

  

Getting ready with the enhanced ECMAScript Node.js console

The node-console module for Node.js provide you with a live console through a convenient and friendly web interface. You can read more about the node-console module in my previous article "Console: handling Javascript Node.js runtime like a pro".

The Node.js console module has ECMAScript 6 and 7 support built in through Babel.js: it simply works out of the box.

To get it working and start playing with new Javascript features, just follow next steps.

  1. create a new folder, open a terminal within it and install node-console module:

    Install node-console module from npm
    npm install node-console
  2. create a new file in the same folder, e.g. "console.js" file, and include the code:

    Source code for a empty application that just start the console web interface
    // pin require function to global object to expose it to the console
    global.require = require;
     
    // load and start the node-console module with default settings
    require('node-console').start();
  3. open your Google Chrome browser and navigate at http://127.0.0.1:9090/
  4. start experimenting Javascript with ECMAScript 6 and 7 directly within the console, try this code from the future:

    Snippet of code to experiment ECMAScript 6 and 7
    // define a class
    class Dream extends Array {
      // concatenated arguments
      constructor (source, ...args){
        // parameter spreading
        console.log(...['getting tired by %s', source]);
        // super class
        super(...args);
      };
      // method override
      push (item) {
        // constants
        const exclamation = '!'; 
        // template string with interpolated variable bindings
        console.log(`impressed by ${item + exclamation}`);
        super.push(item);
      };
      // default value for arguments
      sleep (safe, ms=5000) {
        // promise support
        return new Promise(function (resolve, reject) {
          // arrow function
          setTimeout(() => resolve(safe ? 'dream' : 'nightmare'), ms);
        });
      };
    }
     
    // destructuring variables
    var [dream, name] = [new Dream('tv'), 'Bob'];
     
    dream.push('cake');
     
    // async function
    async function sleep(instance, ...args) {
      console.log('falling asleep...');
      // await operator
      return await instance.sleep(...args);
    }
     
    // await operator (assignment)
    var what = await sleep(dream, true);
     
    // multiline template string with interpolated variables
    console.log(`awake from...
    a ${what} of ${dream[0]}!`);
  5. wonder it just works...

  

Advanced Node.js console behaviors for new ECMAScript features

Promises

The Node.js console features Promise built-in support. When the evaluated code returns a Promise, it does not return the Promise object itself but waits and:

  • returns resolved value when promise is resolved;
  • log exception when promise is rejected.

Promise handling support in Node.js console
// define a function that returns a promise
function getPromise(error) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if (error) {
        reject(error);
      } else {
        resolve('hello there!');
      }
    }, 1000);
  });
};
 
getPromise();
// > outputs 'hello there!' after 1 second
 
getPromise(new Error('oops'));
// > outputs a caught exception after 1 second
Warning

To provide proper support for awaitable functions (async) in Node.js console, the promise handling implementation just returns the first value passed to the "resolve" method.

Promise handling supports only one resolved value in Node.js console
// define a function that returns a promise that will resolve with multiple values
function getMultiPromise() {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      resolve('a', 'b');
    }, ms);
  });
};
 
// console will output just the first resolved value (e.g. 'a')
getMultiPromise();
// > outputs 'a' (not 'b')

  

Await operator

The current implementation of experimental async/await is based on promises. An async function actually returns a promise that will be:

  • rejected: in case of exception thrown within function body execution;
  • resolved: by any return statement within the function body.

The code input from the console is wrapped and evaluated within an anonymous async function:

Node.js console wrapper for ECMAscript 6 and 7
(async function(){
 
  // your code input from console
 
})();
 

So, you can safely input code with await operator.

Await operator input in console
// define global sleep function that returns a promise
global.sleep = function(error, ms=5000) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if (!error) {
        resolve();
      } else {
        reject(error);
      }
    }, ms);
  });
};
 
await sleep();
await sleep(new Error('oops'));

  

Useful readings to learn and experiment ECMAScript 6 and 7

If you want to delve into ECMAScript 6 and 7, some great starting points follow.

Learning ECMAScript 6 features in Node.js console

Featured article, ready snippets to use on Node.js console.

Learning ECMAScript 7 features in Node.js console

Featured article, ready snippets to use on Node.js console.

Babel.js tutorials

You should carefully read examples, they do not work out of the box.

ECMAScript compatibility table

Useful to check out whether some feature is available in a specific platform or not.

Mozilla ECMAScript 6 support

Includes explaination and code sample, remember that you're playing with Node.js not Firefox.

Mozilla ECMAScript 7 support

Includes explaination and code sample, remember that you're playing with Node.js not Firefox.

    

Troubleshooting Node.js console

If you are experiencing problems with Node.js console module, please check its dedicated troubleshooting section.

ECMAScript 6 and 7 specific issues are reported below.

Some ECMAScript features not working

Remember that the support for some latest and, more important, experimental ECMAScript features can't be implemented without natives.

Please check on Babel.js documentation and experimental usage whether the feature is supported and whether limits applies.

  

If you are experiencing any other problem, please contact me so we can extend this section.

You can also report bugs or feature requests directly at the GitHub project page.

  

Further readings and related articles