Node.js v10

Node 10 was released last year and it’s going to be enter the LTS phase this October. So it is about time to fresh up on some of the Node 10 features and start rolling out to production environments if you haven’t done so already. I am going to list the most important ones down below with details and also some examples:

  • Error handling
  • N-api official support
  • HTTP/2 support
  • V8 engine performance boost
  • ESM modules
  • Experimental fs native promises
  • New console method

Error handling

It’s no secret that node has’t been particularly great with error handling and more specifically error objects. You could’ve checked on the message but that’s clumsy and far from ideal. Most folks out there ended up writing their own libraries to handle errors in a more elegant manner. That’s no longer the case as Error got some attention in Node 10.
There are now a couple of error types: ReferenceError, SyntaxError, RangeError while the Error object has been extended and supports now the following properties:

  • code <string> The string error code
  • errno <number> The system-provided error number
  • message <string> A system-provided human readable description of the error
  • syscall <string> The name of the system call that triggered the error
  • path <Buffer> When reporting a file system error, the path will identify the file path.
  • dest <Buffer> When reporting a file system error, the dest will identify the file path destination (if any).

Probably out of this the greatest addition is the error code which is now a part of a big list of predefined error codes which can be checked upon. The full list here.

N-api full support

N-api is a set of APIs used to build addons for Node. This feature was experimental in the previous version of Node, but now, it’s out there. What’s great about these addons is that are written in C++ and can be used like ordinary node modules. As we know, C++ is much faster than Javascript when it comes to intensive CPU work such as image rendering or processing. Node already had a way to integrate C++ addons but it was rather complicated and the communication was done via the V8 engine. The N-api allows you to write Node addons independent of that, meaning that once the library is compiled you can use it with future versions of Node because it works natively.
I think this is still in the beginning and although there is some documentation, there are not that many examples so I wrote a few and put them here.

HTTP/2 support

As a modern development ecosystem Node was due for this, as the standard was approved May 2015. A summary of benefits that HTTP/2 brings to the internet can be found here.

V8 engine upgrade

As you are fully aware already, Node is powered the V8 engine found in Chromium and Node 10 ships out with V6.6 (latest is 6.8 at the time of the writing). This include a couple of Javascript language features around strings and exception handling as well as also some performance boosts around compilation times, promises and async features. A more detailed review of the changes in the V6.6 version can be found here.

ESM experimental modules support

With ES6 introduction in 2015, a new way of importing and exporting modules has been introduced and Node is struggling implementing it ever since. I am talking about this import/export vs require and module.exports. It’s still ongoing and you can try it out using the experimental flag on node but to me the integration is still ugly at this point.

Experimental fs native promises

This is great news, although still experimental we are finally going to see the fs module with promises. Previously you either had to use the callbacks version (I know you didn’t like it!) or somehow get it promisified.

New console method

Console got a new method which can be helpful if you want to print out data in table format. I’ve put an example below, for more please refer to the official documentation here.

// ┌─────────────┬──────┬─────┐
// │ (index) │ username│ password│
// ├─────────────┼──────┼─────┤
// │ 0          │ ‘user1’        │ ‘pass’      │
// │ 1          │ ‘user2’        │ ‘myPass’ │
// └─────────────┴──────┴─────┘

And of course Node 10 ships out with the latest and greatest npm 6. Happy coding!

Node.js: Promises vs Callbacks

If you know a thing or two about node.js is that it’s an asynchronous event-driven environment that some love and some hate. Node’s approach to asynchronous operations is very different from what you might be used to from languages such as C# or Java where you have threads and everything around that. As you know, Node is single-threaded so if you’re running long-lasting operations on the main thread, the application, be it service or UI will be blocked/frozen for the entire time which in turn leads to poor user experience. So Node was making use of callback up until last year when ES6 introduced lots of new features including promises.

Callbacks are functions which are called at the end of long-lasting operation such as IO operations: reading/writing to a file, calling another service via HTTP(s) etc. Let’s see an example of synchronous vs asynchronous code with callbacks.

In the above snippet the final message will be displayed after the file was read, time in which everything else is blocked. Let’s imagine now that this piece of code is inside a service. That means that as long as that file is read, the service is unresponsive.

The snippet above contains a callback which in this case is an anonymous function, but this can be rewritten in many different ways, with a defined function or with array functions (lambdas) but that is not relevant here. What is relevant is the message “finish” will be displayed on screen immediately while the message “read” will be displayed only after the entire file was read and thus allowing other operations to take place while other long running operations are executing. If you do the same exercise with the service this means you have a responsive service that can serve multiple requests in parallel.
Pretty neat wouldn’t you say? Sure, but there is an issue. Nesting and consequently readability and what is called callback hell. A callback hell or nightmare is when you call a function inside a function inside a function. Let’s have a quick example:

So you can see how quickly it can spiral out of control and honestly I have seen way worse. Sure, there are ways to get around that but still you can still end up in a call back nightmare situation.
So what’s the answer? Well, with the introduction of promises you can now chain those events in an even more natural and expressive way. So the code above can turn into the following:

So all of the sudden this became linear, easy to read and to reason about. This is what is called promise chaining where multiple promises are chained together with the purpose that at end you’ll return a promise or throw an exception. Testing becomes naturally nicer since you don’t have the annoying “done” callbacks if you are using the mocha testing framework.
Promises have handlers and states. The states and their corresponding handlers are:

  • pending
  • fulfilled/resolved corresponds to then.
  • failed/rejected  corresponds to catch

Promises come by default in Node but there are libraries that can help you with promises. Most popular ones are Q and bluebird. They can even turn callbacks into promises.
Even though that is nice enough, it can be better by the use of the keywords await/async which makes asynchronous code look synchronous but will not get into that now. The main reason is that people have enough trouble understand Node’s callbacks model and later on the promise model to further confuse with the new features of ES7.

In the mean time, happy promisifying!

The cool world of node.js

Hello! If you know me or if you have read my blog you know I like C#, a lot. However …
I cannot help to notice that C# has its shortcomings especially when it comes around web, webservices and usually it’s not particularly easy to do simple stuff and sometimes comes with a lot of code, code which you don’t really need. I have been experimenting with node.js in the past couple of weeks and I could already see some strengths which blow C# out of the water. I’ll go through some of those strengths, my experience with the language and maybe I’ll even start some tutorials on it as javascript has become my second favorite language of development. You may want to read this paragraph again, hah.

Things I really like about node.js:

  • great package manager(npm). Specify your dependencies in a json file(package.json) and run npm install and all your dependencies are there. That easy!
  • very fast. To understand this: I have this little thing in C# and while I use multiple threads in took more than 5 minutes to complete. Did the same thing in node.js and it was completed in less than one minute. What?!?! Development time was considerably shorter and I could even argue that number of lines of code was considerably shorter even though node.js is much newer to me compared to C#.
  • inherently asynchronous but single threaded. Goodbye thread synchronization issues but be careful to heavy cpu work as it can render your application unresponsive
  • it has some sort of LINQ called ArrowFunctions. We all love lambdas!
  • lightweight libraries for frontend, backend and everything else
  • very very very easy to use with json data format.
  • sure it’s cross-platform
  • very easy to build APIs

For development I used Webstorm because it gives the feeling of an IDE with debugging, watcher and everything nice. But feel free any text editor with some javascript plugin. You can get Webstorm for free if you are doing open source projects or use it for education purposes.

As a conclusion I’d say that the most impressive thing about node.js is the simplicity with which you can build stuff, not to mention speed. I am sure there are shortcomings to this technology as well but I am yet to discover.

See you soon on get started with node.js.

npm start

 

Simple Share Buttons