Using newer ES6 features in Node

Posted by on Jul 8, 2016 in JavaScript, WebDev

If you’re writing Node and want to use some of the newer ES6 features then you may have an issue running some of the newer features that haven’t made it into the V8 engine integrated with your specific version of Node.
I came across this recently when using the new default parameters feature.

Using the latest stable version of node (4.4 at the time of writing), the following code was throwing an error at runtime:

Essentially I wanted the callback parameter to be optional so that I could supply it if I wanted to and it would get invoked, but not throw any errors if not. Using default parameters meant I didn’t have to clutter up my code with lots of null checking and ugly if statements. This is a pattern I use quite a lot in ES6 and feel it leads to much cleaner code.

Node was complaining of the unexpected token callback=() as it didn’t understand the assignment of the anonymous function to the callback parameter (i.e. the default value).

After a bit of digging it became clear that there were two ways around this problem, both of which worked for me. Initially I sidestepped the issue by using the new harmony feature flags, which turns on the experimental features in unsupported versions of v8.
Thus, in my case simply adding the default-parameters flag worked around this problem:

However, the harmony feature flags aren’t really recommended as its putting alpha level code into the fray. The longer term solution (and the route I took) was to upgrade node to the newest version. Again, at the time of writing this is 6.3.0 which has a much, much broader level of ES6 compatibility due to its newer build and newer version of V8.

Problem solved. ES6 and beyond.