O que está por vir na versão v0.12 do Node: uma visão geral dos novos recursos

Junto à comunidade, a StrongLoop está empolgada para ver a versão v0.12 do Node disponível.

O que há de novo?

Não há tempo melhor que o presente para se familiarizar com os novos recursos que estão por vir na versão v0.12. A seguir há uma lista compilada para ajudá-lo a se preparar:

  • Cluster de balanceamento de carga round-robin
  • Otimizações de desempenho
  • Execução de múltiplas instâncias em um único processo
  • execSync: uma API síncrona para processos filho
  • Depugando aplicativos em cluster com Node Inspetor

Cluster de balanceamento de carga round-robin

Ben Noordhuis

Uma das metas de clusterização no Node foi de tornar mais fácil a criação de servidores multi-processos fire and forget. Em um mundo perfeito, você deveria ser capaz de pegar uma aplicação existente de processo único e desovar quantos processos worker quiser sem ter a necessidade de alterar uma única linha de código. O módulo de cluster do Node v0.11.2 introduz uma abordagem de rodízio round-robin: novas conexões são aceitas pelo processo mestre, que em seguida, seleciona um processo worker para entregar à conexão.

Leia mais…

Otimizações de desempenho

Ben Noordhuis

O longo ciclo de desenvolvimento da versão v0.12 tem dado ao time core e aos colaboradores uma ampla oportunidade de apresentar uma série de otimizações de desempenho. Este blog destina-se à cobertura das otimizações mais notáveis. Aqui estão as seis melhorias de desempenho para você ficar ciente:

  • Suporte cork para streams de escrita
  • Melhorias de desempenho em TLS
  • Melhorias de desempenho em Crypto
  • Redução de tensão do garbage collector
  • Melhor desempenho de cluster
  • Temporizadores mais rápidos

Leia mais…

Execução de múltiplas instâncias em um único processo

Ben Noordhuis

Um recurso que é bastante solicitado é a capacidade de incorporar o Node em outras aplicações, em especial de uma maneira que permita a integração com outros loops de evento e com suporte para múltiplos contextos de execução: ou seja, a capacidade de ter várias instâncias Node coexistindo pacificamente dentro do mesmo processo. Imagine uma aplicação node-webkit, onde cada janela executa sua própria instância de Node e que fique isolada de todas as outras janelas. Ou imagine o Node sendo incorporado em um telefone ou num switch de rede onde há a execução de lógica de roteamento para múltiplas conexões, mas em um único processo (o que não está muito longe).

GitHub veio até nós precisando desse tipo de funcionalidade para o Atom.io. É pedir demais, justamente porque o Node começou como – e ainda é – uma aplicação single-threaded (de uma única thread), construído em torno do conceito de um único loop de evento, e com centenas de variáveis globais que armazenam vários bits de estado.

Leia mais…

execSync: uma API síncrona para processos filho

Bert Belder

Apesar do Node ter sido primeiramente inventado para escrever servidores web, os desenvolvedores já descobriram outros casos de uso para utilizá-lo. Surpreendentemente, um desses casos de uso é a alternativa para escrever scripts shell. E há sentido pra isso: o suporte multi-plataforma do Node é muito bom, e quando estamos escrevendo o frontend e o backend, ambos em JavaScript, não seria legal escrever também o sistema de compilação em JavaScript?

Uma notável biblioteca que suporta este caso de uso é o Grunt, o qual é construído em cima do ShellJS. No entanto, o ShellJS é um osso duro de roer: o Node obriga-o a usar assincronicidade nas operações de entrada e saída (operações I/O). E isso é ótimo para servidores web que devem permanecer sensível a todo o momento, porém isso não faz muito sentido para scripts shell, que exigem que todos os passos sejam feitos em sequência. A ineficiência e a feiúra desse hack motivaram a equipe do Node core a implementar uma solução real – a versão v0.12 do Node deve finalmente oferecer suporte à execução síncrona de processos filho.

Leia mais…

Depugando aplicações em cluster com o Node Inspetor

Miroslav Bajtos

Agora, a maioria de vocês já descobriram como que usa o mais recente e melhorado node-inspetor(construído com ferramentas de desenvolvimento do Google Blink) para debugar aplicações Node. Mas que tal aplicações clusterizadas? Neste blog vamos apresentar o que é preciso ser feito para realizar esta façanha.

Leia mais…

Além da versão v0.12 do Node.js: reflexões sobre um roteiro para o futuro

Bert Belder

A equipe StrongLoop recebeu uma grande quantidade de feedback da comunidade no ano passado e ultimamente nós (equipe StrongLoop) temos pensado muito sobre esses feedbacks. Nós perguntamos a nós mesmo “como que pode uma empresa, desenvolvedores individuais e membros de uma comunidade ser os contribuidores mais ativos do Node que consequentemente beneficia a todos? Desde desenvolvedores individuais a clientes de um ecossistema de fornecedores que oferece serviços e produtos ao redor do Node?”

O resultado é este post onde nós já colaboramos com colegas de trabalhos, tanto dentro quanto fora da StrongLoop, para tentar articular o que achamos que a StrongLoop pode fazer de mais útil para ajudar a comunidade a levar o Node para um outro nível. Aqui está o nosso pensamento para APIs, gerenciamento de módulo, instrumentação, ferramentas e conectividade.

Leia mais…

Quando a versão v0.12 vai ser lançado?

Boa pergunta. O primeiro build do que será o Node v0.12 foi lançada há um ano atrás, em abril de 2013. A StrongLoop andou ocupada ajudando a tornar a versão v0.12 uma realidade, fazendo contribuições significativas para o núcleo e também sendo um dos principais autores para um monte de recursos legais como otimizações de desempenhocluster round-robin e a capacidade de executar processos filho de forma síncrona. Embora contribuímos com muitos códigos, nós atualmente não controlamos quando a versão v0.12 será lançada. Esta tarefa cabe ao administrador da comunidade. Os desenvolvedores têm sugerido há alguns meses que a versão v0.12 “será lançada em semanas”. Com cerca de 830 bugs abertos e cerca de 187 solicitações de pull requests, à espera de ser revisto, o que parece ser algo bem improvável. O tempo que dirá!

Use StrongOps para monitorar aplicações Node

Pronto para começar a monitorar loops de evento, gerenciar clusters e perseguir os vazamentos de memória? Nós fizemos isso de tal forma que fique bem mais fácil com o StrongOps tanto localmente quanto na sua nuvem favorita, simplesmente com um npm install.

Event Loop

E o que mais?

  • Pronto para desenvolver APIs e deixá-las conectadas aos seus dados? Confira o framework LoopBack. E veja como que fica mais fácil começar uma API tanto localmente quanto na nuvem, simplesmente com um npm install.
  • Precisa de treinamento e certificação em Node? Saiba mais sobre ambos com as opções de ofertas da StrongLoop.

O que há de novo na versão v0.12 do Node – execSync: uma API síncrona para processos filho

Apesar do Node ter sido primeiramente inventado para escrever servidores web, os desenvolvedores já descobriram outros casos de uso para utilizá-lo. Surpreendentemente, um desses casos de uso é a alternativa para escrever scripts shell. E há sentido pra isso: o suporte multi-plataforma do Node é muito bom, e quando estamos escrevendo o frontend e o backend, ambos em JavaScript, não seria legal escrever também o sistema de compilação em JavaScript?

Assincronicidade é ruim em scripts shell

Uma notável biblioteca que suporta este caso de uso é o Grunt, o qual é construído em cima do ShellJS. No entanto, o ShellJS é um osso duro de roer: o Node obriga-o a usar assincronicidade nas operações de entrada e saída (operações I/O). E isso é ótimo para servidores web que devem permanecer sensível a todo o momento, porém isso não faz muito sentido para scripts shell, que exigem que todos os passos sejam feitos em sequência.

Então, os autores do ShellJS encontraram uma solução “interessante” que permite executar um comando shell e esperar a execução desse comando. De forma geral, isto se resume a:

Em outras palavras, enquanto o shell estiver executando o comando, o ShellJS permanece ativo e continua pesquisando no sistema de arquivos algum arquivo que indica se o comando foi concluído. Como se fosse burro.

A ineficiência e a feiúra desse hack motivaram a equipe do Node core a implementar uma solução real – a versão v0.12 do Node deve finalmente oferecer suporte à execução síncrona de processos filho. Isto na verdade está no roteiro há um longo tempo – lembro de ter sentado na JSConf.eu em 2011 (!) com um dos mantenedores do Node, agora aposentado, Felix Geisendoerfer, esboçando uma forma de como implementar o execSync. E agora, finalmente, após dois anos, o recurso está na branch master.

Parabéns a equipe do ShellJS por essa grande pesca! 🙂

Read more

Installing Node.js and StrongLoop on Windows

Although an increasing number of large companies are greenlighting API projects that leverage Node.js, most installation guides for Node are written with the assumption that the engineer is developing on a Mac and deploying to a Linux machine. For engineers who by choice or because of corporate policy use Windows as their development environment, here’s a quick tutorial that walks you through the installation of Node, StrongLoop tools and their required dependencies you aren’t likely to find on a typical Windows machine.

Step 1: Install Python

Python 2.7 (not 3.x or 2.6.x or before) is required by npm to install packages with compiled addons (like strong-agent or websocket support).

  1. Go to python.org and download the latest stable 2.7.x Windows MSI Installer, either x86 or x86-64, whichever is appropriate for your system.
  2. Run the installer and make sure to add Python to your PATH
  3. Accept default “Install for all users”
  4. Accept default “c:\Python27” for Python files
  5. Enable non-default “Add python.exe to Path”

Step 2: Install Git

Git is required by npm to download packages from GitHub. Such packages are rare, but exist and installing git will allow them to be installed.

  1. Go to git-scm.com and select the download for Windows (currently this is version 1.9.4)
  2. Run the installer
  3. Accept default install location
  4. Accept or modify Components
  5. Accept start menu folder
  6. Modify “Adjusting your PATH environment” to “Use Git from Windows Command Prompt”
  7. Accept default “Configuring the line ending conversions”

Step 3: Install Visual Studio

Visual Studio 2012 or later is required by npm to install packages with compiled addons. Please note that gcc, mingw, cygwin, and other ports of non-Microsoft compilers to Windows are not supported by Node.

If you are currently running Windows 7 and 8, use Microsoft Visual Studio C++ 2013 for Windows Desktop (Express). Visual Studio Express is free and more than adequate to support Node.

  1. Download Visual Studio
  2. Select “Download” and then “wdexpress_full.exe”…if the download doesn’t start, select the “click here” link, then on the next download page, select the “click here” link beside “wdexpress_full.exe”.
  3. Run the installer and accept the default location. This is a big installation and can take a long time, so this might be a good time to go grab some lunch!

Step 4: Install Node

Go to nodejs.org, download and install the latest “Windows Installer (.msi)” appropriate for your system.

Step 5: Install StrongLoop

After installing the above tools restart your machine to make sure your new configurations have taken effect.

  1. Open up a Windows command shell
  2. Install slc with npm install -g strongloop…Please note that warnings related to the installation of node-syslog can be ignored, they are expected on Windows.
  3. Run slc -v …you should see a listing of the StrongLoop components and their versions.

Congratulations, you now have Node.js, StrongLoop and its dependencies installed! You are ready to Get Started!

Troubleshooting

If you encounter any difficulties installing StrongLoop try some of the tips below.

1. Restart Windows, to ensure configuration has taken effect.

2. Verify dependencies are installed:

  • python --version: should be 2.7.x
  • node --version should be v0.10.x or v0.12.x (Once it is released)
  • npm --version should be 1.x or 2.x (Once Node v0.12 is released)

3. Ensure a simple npm package can be installed:

  • npm install -g semver
  • semver --help should print usage message

4. Ensure a simple Node compiled addon can be installed:

  • npm install -g buffertools should compile and install without errors.

If you are still having issues, please report the result to callback@strongloop.com. If it was npm install that failed, please attach the npm-debug.log file left by npm.

Tips and Tricks

1. If you have multiple versions of python installed, you can select which on is used by npm for building compiled addons:

  • npm config set python c:/Python2.7/python

2. If you have multiple versions of Microsoft Visual Studio installed, you can select which one is used by npm for building compiled addons:

  • set GYP_MSVS_VERSION=2012 or
  • Append npm --msvs_version=2012 or --msvs_version=2013 (as appropriate) to the end of npm install commands, for example: npm install -g strongloop --msvs_version=2012

What’s next?

  • Ready to develop APIs in Node.js and get them connected to your data? Check out the Node.js LoopBack framework. We’ve made it easy to get started either locally or on your favorite cloud, with a simple npm install.

 

Getting Started with Contributing to LoopBack Documentation

As famously observed in the seminal book The Cathedral and the Bazaar, developing software in the open source “bazaar” provides many advantages.  The benefits of open development are now widely recognized and have been key to the success of Node and web technology in general.  At StrongLoop, we’re strong believers in open development, and we’re developing almost all our software, including the LoopBack Node application framework, as open-source projects.

Unfortunately, it’s also widely known that the quality of open-source project documentation is often lacking.  As a technical writer with over 20 years experience in developer docs, I’ve observed that documentation is the “red-headed stepchild” of the software world.  Too often, it’s an afterthought, and rarely takes priority.  Developers need it and feel the pain when it’s poor, but actually writing good documentation is easier said than done.

StrongLoop recognizes the importance of good documentation, which is why we’re devoting substantial resources and effort to improve LoopBack’s documentation.  Making good docs is often labor-intensive, particularly for a complex and powerful application framework like LoopBack.  The reality is that, as a small start-up, StrongLoop has limited resources, and only one full-time technical writer (me) for many disparate projects, including LoopBack, Express, StrongLoop’s Node Ops solutions (StrongLoop Controller and StrongLoop Agent), and other products.

To help ensure that LoopBack has the best documentation possible, we’re going to leverage the power of open development.  We’re opening up the LoopBack documentation on docs.strongloop.com to community edits.  We’d love to hear your ideas about what to do in GitHub, or on the LoopBack Google Group.  Even more, we’d like to see the community become actively involved in improving the docs.  We invite you to login to our wiki at docs.strongloop.com with username “community” and password “strongloop”.   Please read Contributing to LoopBack documentation before editing.

LoopBack’s API docs are created from comments in the code.  So, contributing to the API docs is just like making a code contribution–use a PR in GitHub.

Win swag

To kick start contributions, we’re offering LoopBack swag to the best contributors:

  • Make a small fix (correction or addition) and we’ll send you a LoopBack sticker.
  • Make a significant improvement (new or improved example code, new section, fixing one of the known doc issues),  and we’ll send you a T-Shirt.
  • Make an extra-awesome contribution and we’ll send you a StrongLoop hoodie.

Who gets what is at our sole discretion, but we really want to encourage participation, so rest assured we will reward good-faith efforts.

IMPORTANT: Be sure to provide your email or GitHub ID in the comment field when you make the contribution.  Since we’re using a shared login, this is only way to ensure you get credit for your work!  See Contributing to LoopBack documentation for details.

What we’ve done lately

If you’ve been keeping up with the LoopBack Google Group, you know that we’ve focussed special effort on documentation lately.   The whole team took a sprint to work primarily on docs.  We did quite a bit of reorganization and cleanup, and among other things wrote and expanded several articles on how to implement custom logic before responding to client requests, including:

We’ve also added a lot of examples with accompanying tutorials. We’re working on a more advanced comprehensive example.

What is complete documentation?

For developer docs, there’s often even disagreement about what “complete documentation” means.  I’ve actually had developers tell me “the code IS the documentation!”  Of course, that’s a rather extreme (and, one hopes, facetious) view but, especially in the case of small open-source projects, might not be too far from the mark.

At the most basic level, “documentation” means just API documentation: what are the functions, their signatures, options, defaults, return values, and so on.   For any substantial project, API docs are necessary, but not sufficient.  API docs are no more “documentation” than flour, eggs, milk, and sugar are cake.

Beyond API docs, you also need to create “recipes” for using the API, with reference to the API docs.  These “how to” articles are procedural and task-oriented.  This is the cookbook that shows you how to turn the API “ingredients” into delicious chocolate cake–in our case, an awesome LoopBack application.  Related documentation includes conceptual docs that explain concepts or principles behind the recipes.

Finally, the “icing on the cake,” as it were, are tutorials that walk you through the steps to create applications with basic features.   Tutorials are important tools for teaching but take the most time to write.  Typically, the tutorial is the last thing you can write, depending on how well-defined the “developer experience” is.

We welcome contributions in all these areas, and we’ll keep you posted on progress.  Together, we can bring the quality of LoopBack’s documentation up to par with that of the framework itself.

What’s next?

  • Ready to develop APIs in Node.js and get them connected to your data? Check out the Node.js LoopBack framework. We’ve made it easy to get started either locally or on your favorite cloud, with a simple npm install.

 

Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More

javascript-templates-2014

Lets talk templates, specifically JavaScript powered templates. Even more specifically – template engines that work as well on the server side as they do on the client side. After all, this is the great promise and advantage that isomorphic JavaScript brings to the table – ability to run the same code everywhere.

The big benefit of such approach when it comes to templates specifically is being able to render HTML on the server side, send it over the wire to a client and then have that client interact with the page and have it change using the same template bits and maybe even some shared logic. That can be a huge gain in terms of effort and reduces footprint of your application.

In this article I want to look at some of the most popular JavaScript templating engines. It’s not my intent to compare them or do some silly benchmarking. I don’t think subjectively evaluating a bunch of templating engines and picking the one I like best is helpful in any way. Most of the engines bring something unique to the table and my idea of DRY might not necessarily match yours.

Having said that, the template engines in this articles were selected based on a simple “GitHub score”. How was that determined you might ask? I’ve come up with a simple formula:

Finally, the last criteria for selection is project activity in general. I decided not to work that into the formula to keep things simple. There are a few engines that were excluded based on the lack of any activity over an extensive amount of time such as Eco and Haml.js. These could be considered abandoned in my opinion. EJS and Mustache.js get a break here because they are fairly simple and there aren’t any new features in general.

With that in mind, I’m going to give a brief sample of what markup looks like for each engine, the minimum code necessary to render that markup to HTML followed by some pros and cons.

Please note, everything in this article represents my personal opinion and might not match yours. The purpose here is to show you different templating languages, give you my personal take on each and let your decide for yourself.

JavaScript Template Engines 2014

Name Stars Forks Commits Contributors GitHub Score
Jade 7,335 1,136 1,968 135 118
Mustache.js 6,985 1,464 514 55 95
Dust.js 1,571 293 697 28 28
Nunjucks 1,565 115 525 40 26
EJS 1,796 289 221 24 25

Jade

jade

Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for Node.

Pros

  • No closing tags
  • White space significant indentation
  • Extensive layout inheritance
  • Macros support
  • Plain old school includes
  • Built in support for Markdown, CoffeeScript and others
  • Available implementations in php, scala, ruby, python and java.

Cons

  • Not everyone likes significant white space
  • JavaScript inlining can get cumbersome for more than one line
  • Requires a small runtime to use precompiled templates on the client
  • Not suitable for non-HTML output
  • No streaming support
  • Somewhat high learning curve

Tools

Summary

Jade takes Haml DRYness to the next level and gets rid of leading % character but otherwise it’s pretty much on par feature wise. Jade ended up at the top of the list based on the numbers. I liked that there’s no need to worry about closing tags and significant white space enforces clear coding convention between team members. Jade allows for full JavaScript expressions but makes that just awkward enough to discourage full blown logic in the views. It’s support for inlined Markdown and CoffeeScript is a nice addition. Ability to use Markdown for larger blocks of text makes formatting a pleasure.

Mustache.js

mustache

Mustache.js is an implementation of the Mustache template system in JavaScript.

Mustache is a logic-less template syntax. It can be used for HTML, config files, source code – anything. It works by expanding tags in a template using values provided in a hash or object.

We call it “logic-less” because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

By {{fullName author}}

 

{{body}}

 

Comments

{{#each comments}}

By {{fullName author}}

 

{{body}}

{{/each}}

Pros

Cons

  • Cumbersom partials system requires to register all partials
  • Default global namespace for partials will require workaround to avoid collisions
  • No built-in layout system
  • Have to close your own tags (right?)
  • No streaming support

Implementations

There are a few other Mustache implementations that stand out and are worth noting:

  • Handlebars.js adds a couple of additional features to make writing templates easier and also changes a tiny detail of how partials work.
  • Hogan.js was written by the good folks at Twitter to meet three templating library requirements: good performance, standalone template objects, and a parser API.

Tools

Summary

I don’t think it’s a valid statement to claim that language doesn’t have control structures just because the syntax looks a little different but does essentially the same thing. No sufficiently complex template can get away without using basic ifs & loops and making the loud statement of being “logic-less” is unnecessary and silly in my opinion. Having said that Mustache is a very popular templating language which is evident from its many platform implementations. It has very little learning curve and can be used for things other than HTML.

Dust.js

dust

Dust.js is a heavily influenced by Mustache template language. The original Dust.js repository has been pretty much abandoned but the LinkedIn fork that is listed here is alive and pretty active.

These are your current settings:

    • xxxx

 

  • yyy

 

 

{/bodyContent} {<pageFooter}


About Us | Contact Us {/pageFooter}

Pros

  • Async & streaming support
  • Operating on plain HTML, no significant white space
  • Clean, concise variable and loop controls syntax
  • Could be used for things other than HTML, eg config files, JSON
  • Doesn’t pretend to be logic-less
  • Filters support

Cons

  • Can’t automatically load partials
  • Default global namespace for partials will require workaround to avoid collisions
  • Have to close your own tags (right?)
  • Preloading and naming templates for rendering feels strange
  • Somewhat high learning curve, especially if you want to get into streaming

Tools

Summary

The streaming support in Dust.js is unique. The runnable example takes advantage of this to illustrate how HTML could be streamed to the user. You can stream response by itself and you can stream chunks. You can imagine a case where you render a list of promises resolving them as they are rendered and only resolving those that are rendered. Be sure to read the original documentation because the LinkedIn fork while having a great guide misses on some key points.

Nunjucks

nunjucks

Rich Powerful language with block inheritance, autoescaping, macros, asynchronous control, and more. Heavily inspired by jinja2.

{{ title }}

{% endblock %} {% block content %}

      {% for name, item in items %}

    • {{ name }}: {{ item }}

{% endfor %}

{% endblock %}

Pros

  • Async support
  • Extensive layout inheritance
  • Macros support
  • Plain old school includes
  • Filters support
  • White space control
  • Operating on plain HTML, no significant white space
  • Clean, concise variable and loop controls syntax
  • Could be used for things other than HTML, eg config files, JSON
  • Custom tags support

Cons

  • Have to close your own tags (right?)
  • No streaming support
  • Somewhat high learning curve

Tools

Summary

Nunjucks has the weight of Mozilla behind it and a very extensive documentation. Unlike Dust.js where async support is baked in as a byproduct of the streaming, Nunjucks has a full support for async filters and tags. Your filters could be making database queries and performing other async operations during rendering, which could be pretty powerful when done right.

… custom filters and extensions can do stuff like fetch things from the database, and template rendering is “paused” until the callback is called.

EJS

ejs

Embedded JavaScript templates for node

Users

<% function user(user) { %>

  • <%= user.name %> is a <%= user.age %> year old <%= user.species %>.

 

<% } %>

    <% users.map(user) %>

Pros

  • Operating on plain HTML, no significant white space8 Basically writing JavaScript, few restrictions here
  • Could be used for things other than HTML, eg config files, JSON
  • Filters support
  • No learning curve

Cons

  • No async support
  • Very verbose, PHP-like syntax
  • Includes are loaded from local file system (not even sure how client side is handled in this case)

Tools

Summary

EJS is probably the most old school way of writing templates. Takes me back to the days of PHP and JSP. It’s very verbose and having to close your functions and if statements with <% } %> type of blocks makes the code difficult to read and even more difficult to type. EJS is hands down my least favorite templating language. It can however have its uses because in the bare minimum implementation it’s just about 25 lines long.

One more thing…

react

There’s one other project that I haven’t mentioned that I feel is worth noting – React by Facebook. I don’t feel it completely belongs on this list because it’s so much more than a templating engine. However, because it can actually be used as an isomorphic rendering engine, it’s worth noting. It’s currently very actively developed and there’s a ton of buzz around it.

Summary

Name Stars Forks Commits Contributors GitHub Score
Jade 7,335 1,136 1,968 135 118
Mustache.js 6,985 1,464 514 55 95
Dust.js 1,571 293 697 28 28
Nunjucks 1,565 115 525 40 26
EJS 1,796 289 221 24 25

So what do we have? Five different isomorphic template engines written in JavaScript that take completely different approach to essentially doing the same thing – rendering HTML. From the most basic EJS, a very popular Mustache.js, LinkedIn backed Dust.js, Mozilla produced Nunjucks and a fully independent and most popular of the bunch – Jade.

All of them have their own strengths and weaknesses, some of them could even be used together with others. Dust.js stands out of the crowd with its streaming support. Jade has significant white space and can seamlessly integrate with other markup engines like Markdown and CoffeeScript. Nunjucks brings async filters and tags to the table and Mustache.js is minimal and straight forward. EJS is just… well, EJS I guess – it’s a bare bones templating engine.

Finally, I’ve put together a runnable example. Every engine listed is set to produce exactly the same output to give you and idea of where they differ. Dust.js is slowed down on purpose to illustrate it’s streaming capabilities. The source is also posted on GitHub.

What’s next?

  • Ready to develop APIs in Node.js and get them connected to your data? Check out the Node.js LoopBack framework. We’ve made it easy to get started either locally or on your favorite cloud, with a simple npm install.