DailyJS

DailyJS

The JavaScript blog.

Subscribe

@dailyjs

Facebook

Google+

Featured

modules events conferences iojs libraries node npm

Node Roundup: 0.12.5, 0.10.39, io.js 2.3.1, NodeDay, Apey Eye

Posted on .

Node 0.12.5, 0.10.39, io.js 2.3.1

Two new releases of Node just came out. Both releases fix OpenSSL security issues, but 0.12.5 also includes updates for uv and npm.

io.js 2.3.1 was also released this week. One of the big changes in this release is performance improvements for require:

module: The number of syscalls made during a require() have been significantly reduced again (see #1801 from v2.2.0 for previous work), which should lead to a performance improvement (Pierre Inglebert) #1920.

This sounds very nice for large projects.

NodeDay

NodeDay

NodeDay is a conference being held in London on 26th June (this Friday), for free! Speakers include Lin Clark, who writes npm's excellent blog posts, and programmers from the BBC, Red Hat, and other companies that are using Node for interesting things.

nodeday is a Node.js conference by the enterprise, for the enterprise. Now in its second year, this one-day industry conference brings together people from companies that have adopted or are planning to adopt Node.js, and focuses on the issues that these companies face. It gives participants a forum to discuss and share their experiences with Node.js, share advice, tips and tricks, and drive forward both the technology and the community.

I apologise for not writing about this sooner, but I only just found out about it! If you have conferences you want me to cover on DailyJS, you can use the contact forms or message me on Twitter (@alex_young).

I really wanted to go to NodeDay but I can't make it this time.

Apey Eye

Filipe Sousa sent in Apey Eye (GitHub: https://github.com/glazedSolutions/apey-eye, License: MIT, npm: apey-eye):

Apey Eye is an Object-Resource Mapping Node.js API framework that uses next-generation JavaScript features that can be used today, like Classes, Decorators and async/await for maximum expressiveness.

This is a framework for building data layers that map directly to REST APIs. It's a bit like ORM for HTTP. It comes with base classes for routing, REST resources, models, and validation, and the models can serialise data to RethinkDB. To talk to other databases a new base model class would have to be written.

Thanks to ES6, the model syntax is very clean:

let Model = ApeyEye.Model;

class MyModel extends Model {  
    constructor() {
        super(async function() { (...) });
    }

    static async fetch() { (...) }
    static async fetchOne() { (...) }
    async put() { (...) }
    async patch() { (...) }
    async delete() { (...) }
}

To me this looks like C# without the extra syntax for strong typing. The validation API looks similar to what you might have seen before with modules like Mongoose.

I like the idea of object-resource mapping at the HTTP level. In Node web apps we seem to spend a lot of time thinking about HTTP servers and APIs, so this feels like it could reduce the amount of boilerplate required to interface from that step to the database layer.

Featured

node command-line servers libraries

Add a CLI to Node Apps with Vantage

Posted on .

Vantage (GitHub: dthree/vantage, License: MIT, npm: vantage) by David Caccavella is a very nicely packaged module for adding command-line interfaces to your Node applications. It provides two components: a server, and a command-line tool that you use to connect to your live app. Rather than connecting to a TCP port with something like telnet, you actually type vantage in the command-line.

To hook it up to your application, you'll need to add a Vantage server. First, install Vantage to your project (npm install --save vantage), then instantiate a Vantage object and hook up the functionality that you want:

var Vantage = require('vantage');  
var server = new Vantage();

server  
  .command('foo')
  .description('Outputs "bar".')
  .action(function(args, cb) {
    // Do anything: check the database, run migrations, show useful stats
    console.log('bar');
    cb();
  });

server  
  .delimiter('webapp~$')
  .listen(80)
  .show();

I'd put this in a separate file to your main Express/Koa/Hapi/etc. app server, then add Vantage actions for the desired functionality. You could add things like database queries, or heartbeat/usage info, and so on.

Once you've added Vantage to your web app, if you install it globally you'll be able to just type vantage ip:port to connect to your server. Typing help will display the built-in commands and any actions that you've added. You should see something like this for the previous example:

webapp~$ help

  Commands

    help [command]    Provides help for a given command.
    exit [options]    Exists instance of Vantage.
    vantage [server]  Connects to another application running vantage.
    foo               Outputs "bar".

In addition to basic commands and subcommands, Vantage uses inquirer for prompts. Inquirer's prompts are quite powerful: they're ideal for things like yes/no questions and checkboxes. You could use it to force a "yes/no" prompt before a irreversible operation.

Vantage has a few other nice features that'll make your backdoor feel more professional: you can add a banner when people sign in (perhaps with legal warnings, or help), it supports a "firewall" for limiting access, and the documentation has details for using Vantage with Express, Koa, and TLS/SSL.

On the subject of backdoors: Vantage doesn't currently support authentication. It may be possible to use it as a limited informational interface to your server, but I'd strongly recommend binding to internal interfaces only. That means you'd have to ssh to a server, and then run vantage remotely. If that's not possible or convenient, then at least set up TLS/SSL. The current idea for authentication is to support it through middleware -- it already supports middleware so actions can be made reusable, so it seems like a sensible approach.

Authentication issues aside, it definitely seems like something worth using for development servers: I know many people who would love to see their Node web apps get the kind of consoles that popular web frameworks offer (Django's manage.py shell and Rails' console are two that spring to mind). Check it out, but try local/development mode first!

Featured

routing ui libraries

State-Based Routing with abstract-state-router

Posted on .

A few months ago I wrote a custom hash URL router for a React project. We've been trying to plug in a more generalised open source router, but dealing with the state in our particular application has proved problematic. Josh Duff sent in abstract-state-router (GitHub: TehShrike/abstract-state-router, License: WTFPL, npm: abstract-state-router), a general purpose routing library that isn't tied into any specific framework. Josh had been working with Angular, but wanted to use a routing library outside of Angular projects.

This is from Josh's post about the project - Why your webapp needs a state-based router:

I'm a child of the node/npm revolution, and as such I'm pretty framework-averse. I prefer disconnected modules that solve problems that I can compose myself.

I looked for similar libraries, but the only ones I found (react-router and Ember's router) are similarly tied to their chosen rendering/templating tools.

Built with help from ArtskydJ, abstract-state-router is heavily inspired by ui-router, intended to be used with whatever templating library you like. At the time of this writing, renderers have been set up for Ractive.JS, Riot, and virtual-dom - and it's not too difficult to implement new ones with your favorite template/dom manipulation library.

The API uses ideas from ui-router and Express: route names are parsed using ui-router's dot notation, and routes are parsed with a fork of path-to-regexp.

Here's a quick example:

var createStateRouter = require('abstract-state-router');  
var stateRouter = createStateRouter(makeRenderer, rootElement, options);

stateRouter.addState({  
  name: 'app.tab1',
  data: {},
  route: '/tab_1',
  template: '',
  resolve: function(data, parameters, cb) {
    getTab1Data(cb)
  }, activate: function(context) {
    document.getElementById('tab').innerText = context.content
  }
});

In this example, the makeRenderer option is a function that returns an object with four properties: render, destroy, getChildElement, and reset. There's an example of this in the test helpers.

Once you've set up a router, you can browse to a specific state with stateRouter.go. The way state change is handling is documented in the readme in detail, but every state change destroys DOM elements that are no longer valid, and then creates the new states.

To my knowledge abstract-state-router is unique because it focuses on state and defining routes, so it's not tied to any specific framework. Josh said he's willing to help people hook it up to specific UI libraries, so if you want to use it but aren't sure how t implement the rendering code then he may help you out!

Featured

libraries frameworks single-page-apps

Not Really Single Page Apps

Posted on .

Nobody actually makes single page apps in a single page anymore, do they? Some are saying they should really be called native web apps, which sounds fine to me. Anyway, coincidentally two readers sent me their own single page app libraries. They both build applications from separate files, but work in quite different ways.

Griffin.yo (jgauffin/griffin.yo, License: Apache 2.0) by Jonas Gauffin is a framework written in TypeScript that supports templates, view models, routing, and caching of server-side data.

Once views and models have been loaded they are cached in the browser (the cache is emptied if the browser is reloaded). Thus as long as the user continues to use the site as a SPA application everything is only loaded once from the server.

There's a blog post about Griffin.yo that introduces the main ideas, and the examples are written with TypeScript. It uses a project structure that is similar to many other web frameworks. I don't think there's a project generator, so follow the quick start guide if you want to try it out.

The other SPA project I was sent recently is Igaro App (GitHub: igaro/app, License: GPL). The author, Andrew Charnley, claims it's faster than AngularJS, and the current version is 1.0.0.

The thing that makes Igaro different is it's HTML-free. It avoids using DOM query selector methods to try to improve performance, and therefore has no template engine. Instead it uses routes to build pages, and standard CSS for styling and layout.

There's a DOM element creation API, so you can make elements in a way that reminds me of React:

model.managers.dom.mk('p', wrapper,_tr('Localized string'), 'myClassName');  

Objects created by Igaro are decorated with features for two-way parent-child event management, and dependency tracking. You can do this to arbitrary objects by using the bless method. Bless could be used to make widgets that work with Igaro apps.

In terms of ES6 support, Igaro makes heavy use of promises, which makes sense. Given the use of string fragments over templates, I expected to see ES6 template strings. I couldn't find any examples of template strings in Igaro, but given that it has a Grunt-based build system I don't think it would be too hard to add Babel to an Igaro project.

You can see examples in the documentation: all of the documentation pages are written with Igaro, and if you click the curly braces at the top of the page you'll see the raw JavaScript that's used to generate the page.

I think the paradigm shift to "native web apps" is the right way forward for single page web apps. Rather than the community settling into Angular or React it seems like we're making more libraries – and more creative libraries – than ever!

Featured

ES6 announcements

Standard ECMA-262, 6th edition (June 2015)

Posted on .

ECMAScript 6 has been finalised under Standard ECMA-262 6th edition (June 2015). There's no going back now! The JavaScript community can breathe a sigh of relief before gearing up for the next major language revision. Or will we all live in the future using transpilers? Let's take a minute to look at ECMAScript 2015's language features.

Declarations

JavaScript's scoping rules are difficult to understand because var behaves inconsistently depending on scope. The new keywords, let (MDN) and const (MDN), scope based on lexical environment:

Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.

So, not only do you get the extra expressive power of being able to declare constants, but you also get the ability to declare variables according to more natural scoping rules. Basically: let works the way most of us thought var did at some point when we learned JavaScript.

Here's something you can try in a Chrome debugger to see how this works:

(function() {
  'use strict'
  for (let i = 0; i < 3; i++) {
    console.log('loop:', i);
  }
  console.log('after loop:', typeof i);
})();

The last statement will show that i is undefined after the loop. Now try this:

(function() {
  'use strict'
  for (var i = 0; i < 3; i++) {
    console.log('loop:', i);
  }
  console.log('after loop:', typeof i);
})();

You should see that i still exists after the loop. Almost everyone I've ever explained this to has forgotten it within a week. The new wisdom is this: you probably want const! If not let. Let's forget about var and everything will be OK.

Arrow Functions

If you think it's weird that for doesn't exist in the same dimension as var, then what about this in anonymous methods? It's very easy to make the mistake of passing a function to a method and assuming this will be bound to the object that owns the method. What really happens is this becomes the global object.

Arrow functions (MDN) help avoid unbound weirdo global this and also makes anonymous functions more readable:

setTimeout(() => { console.log('Hello'); }, 1000);  

Arrow functions may omit the curly braces when arguments are supplied. Too many callbacks? Do I care when I can just type =>?

Generators

Generator functions (MDN) are ideal for creating functions that should be exited and continued later. They can make asynchronous APIs arguably cleaner, and are starting to be adopted by API designers for things that would be typically callback heavy, like database APIs.

Generator objects are both iterator and iterable: there's a whole section in the spec on iteration, but rather than puzzling over that if you want a solid technical introduction to iteration see Dr. Axel Rauschmayer's Iterables and iterators in ECMAScript 6.

Class syntax

Now you can make classes (MDN) the way you do in other languages. Kind of. Classes support subclassing (extend), and in derived classes you have to call super. Did you know that underneath the minimalist sheen of ES6 classes you'll find good old fashioned prototype chains?

The design of ES6 classes is mostly backwards compatible with existing code, so you don't need to rush around rewriting prototype classes as ES6 classes. However, like arrow functions and the new block scoping, using ES6 classes reduces boilerplate. You'll appreciate that fact when subclassing (there's no goofy constructor function .call, just call super).

Default and Rest Parameters

Speaking of boilerplate, did you know ES6 has default parameters (MDN) and rest (MDN) parameters?

You can now set defaults when defining arguments:

function f(a, b=123, c='a') { console.log(a, b, c); }  
f('a!');  

And here's a "rest" example:

function multiply(multiplier, ...theArgs) {  
  return theArgs.map(function (element) {
    return multiplier * element;
  });
}

var arr = multiply(2, 1, 2, 3);  
console.log(arr); // [2, 4, 6]  

More

Naturally there's a lot more that I don't have time to cover today: maps, weak maps, destructuring, modules, promises, proxies, typed arrays, template strings.

But of course, we're all using promises already! Template strings: grown up interpolation, extremely useful for everything from SQL statements to generating client-side HTML fragments.

Typed arrays relate to JavaScript evolving as a language for dealing with binary data: people have already been using and abusing them for making things like games, synthesisers, and graphics processing.

I saw this great tweet by Eric Elliott (retweeted by Marc Harter, my coauthor on Node.js in Practice) that linked the ES6 announcement with the news about WebAssembly:

WebAssembly, "wasm" for short, .wasm filename suffix, a new binary syntax for low-level safe code, initially co-expressive with asm.js, but in the long run able to diverge from JS's semantics, in order to best serve as common object-level format for multiple source-level programming languages.

It almost feels like JavaScript has changed overnight, except for the fact that ECMAScript 2015 has taken many years of hard work! It could have been more radical, but the standardisation process has kept it largely conservative and backwards compatible. It should also help us solve some of the issues JavaScript has as a language.

Now, if only those Node/io.js guys could get things all merged up so we can start using more ES6 features without having to transpile Node code...