Angular Grid, React Native Introduction

31 Mar 2015 | By Alex Young | Comments | Tags react react-native angular ui

Angular Grid

Angular Gird

Niall Crosby sent in Angular Grid (GitHub: ceolter/angular-grid, License: MIT), a library for managing tables of data with Angular. It supports sorting, filtering, column resizing, CSS themes, and search. There’s even an example that extends the cell renderer to show a file browser view.

Like other data tables, you can specify the columns with JSON and then fetch JSON data from the server to populate the table. Here’s a short Angular example that uses $http to fetch the JSON:

module.controller('tableController', function($scope, $http) {
  var columnDefs = [
    { displayName: 'Athlete', field: 'athlete', width: 150 },
    { displayName: 'Age', field: 'age', width: 90 },
    { displayName: 'Country', field: 'country', width: 120 },
    { displayName: 'Year', field: 'year', width: 90 },
    { displayName: 'Total', field: 'total', width: 100}
  ];

  $scope.gridOptions = {
    columnDefs: columnDefs,
    rowData: []
  };

  $http.get('olympicWinners.json')
    .then(function(res){
      $scope.gridOptions.rowData = res.data;
      $scope.gridOptions.api.onNewRows();
    });
});

There are more examples available in the documentation for Angular Grid.

React Native Introduction Tutorial

John Wu has written an introduction to using React Native with iOS apps. It includes details on how to use it with CocoaPods, and how to wire up the JavaScript view code.

If you’re new to Objective-C and just want to get React Native up and running, then this should help because it walks through all of the necessary setup details. Installing CocoaPods isn’t too hard (it’s an Objective-C package manager), so as long as you can compile and run basic iOS apps you should be good to go. There’s also a sample application on GitHub.

Flow, Frontend Conference, jQuery Conference

30 Mar 2015 | By Alex Young | Comments | Tags libraries types events conferences

Flow

If you like strongly typed languages, then there are more options than ever for JavaScript. Other than TypeScript, a major new tool is Flow (GitHub: facebook/flow, License: BSD) from Facebook. Flow allows you to annotate code with comments to get type checking – this is known as weak mode. You can also use real type annotations, which means you’ll have to use the Flow transpiler to deploy code.

Flow is written with OCaml, and it’s available through the OPAM package manager (opam install flowtype).

If you want type checking without completely changing JavaScript, then you may like TypeScript. There’s even a Flux and React demo:

In this case study, we take an existing React project and attempt to have Flow be able to successfully type check its code. While it will not be an automatic, run the Flow type-checker only one time win, we will show that it does not need to be painful to use Flow on your existing projects.

You Gotta Love Frontend Conference

The You Gotta Love Frontend Conference is being held in Tel Aviv from June 8th through to June 9th, 2015. Tickets are available from 750 NIS, which is about $190. The speakers include Douglas Crockford, Lea Verou, and Martin Kleppe, so it sounds like it’ll be worth attending!

jQuery Conference: San Francisco

Famo.us is hosting a jQuery Conference in San Francisco on June 22nd and 23rd:

Famo.us, the JavaScript framework for building beautiful, high-performance web and mobile UIs, is hosting a jQuery conference on June 22nd - 23rd, 2015 at the Regency Ballroom in San Francisco, CA. Tickets go on sale April 1st at 10am PST. We are releasing a limited number of Super Early Bird tickets for $150. After they sell out, we will offer attendees an Early Bird ticket for a week at $225, before the General Admission tickets go on sale for $350.

This is the official jQuery San Francisco conference, which has its own site here: jquerysf.com.

React Native

27 Mar 2015 | By Alex Young | Comments | Tags react ios android

React Native

The developers at Facebook have been showing off React Native for a few months, but it’s finally been released on GitHub: facebook/react-native. I went to a Facebook tech talk about React Native earlier this month, and as someone who has experience developing iOS apps, I was extremely excited about it.

React Native lets you write React components with JSX that are converted to native views. In the Facebook tech talk, they basically described it as being close to ReactJS but with a few functions changed to output native view code instead of DOM elements. That means React Native apps include a JavaScript runtime. It also uses a flexbox layout model and styling. Styles are not written in CSS but instead use JavaScript objects that will make you think of a JSON version of CSS. Here’s an example:

tyles = StyleSheet.create({
  row: { flexDirection: 'row', margin: 40 },
  image: { width: 40, height: 40, marginRight: 10 },
  text: { flex: 1, justifyContent: 'center'},
  title: { fontSize: 11, fontWeight: 'bold' },
  subtitle: { fontSize: 10 },
});

Working with React Native has several benefits:

  • You can write components with JavaScript
  • Changing views doesn’t require recompilation, you see live updates in the iOS simulator
  • No recompilation is necessary after fixing crashes that are limited to the JavaScript portion of the project

The way I understood React Native was that it would replace the view and “view model” layer of an application. You could theoretically write a lot of JavaScript instead of Objective-C, but it seems better to treat it more like front-end development in a web application. The React Native documentation states that it’s designed to work with custom native views:

It is certainly possible to create a great app using React Native without writing a single line of native code, but React Native is also designed to be easily extended with custom native views and modules - that means you can reuse anything you’ve already built, and can import and use your favorite native libraries. To create a simple module in iOS, create a new class that implements the RCTBridgeModule protocol, and add RCT_EXPORT to the function you want to make available in JavaScript.

There’s a getting started guide which should help you if you just want to try it out right now, but you’ll need to be familiar with Xcode and iOS development.

An Android version is coming, and but will require that your Android apps include the JavaScript runtime. The iOS version is slightly slicker in that the JavaScript runtime is available as part of Apple’s standard libraries (JavaScriptCore).

Standard, propertyinterceptor

26 Mar 2015 | By Alex Young | Comments | Tags node libraries modules style es6

Standard

Feross Aboukhadijeh’s Standard (GitHub: feross/standard, License: MIT, npm: standard) is a zero config linter that checks your code against community conventions:

Adopting standard style means ranking the importance of community conventions higher than personal style, which does not make sense for 100% of projects and development cultures. At the same time, open source can be a hostile place for newbies. Setting up clear, automated contributor expectations makes a project healthier.

Be aware that one of the choices is no semicolons, which I don’t believe is popular enough to be considered a “community convention”. However, key contributors in the Node community do advocate dropping semicolons, so things seem to be moving that way.

This project uses eslint and contains the .eslintrc file so you don’t have to worry about it. In fact, the idea of settling on a standard style guide for a project is sensible and something that can be automated rather than left to the PR/code review stage.

propertyinterceptor

If you use Object.getOwnPropertyDescriptor and Object.defineProperty then you might like Simon Blackwell’s propertyinterceptor (GitHub: anywhichway/propertyinterceptor, License: MIT, npm: propertyinterceptor):

A simple, standardized means of creating reliable chained before and after methods on Javascript object properties for validation, security, functional reactive programming, and more.

It adds the following methods:

  • Object.intercept.afterGet(someObject,someProperty,interceptor)
  • Object.intercept.beforeSet(someObject,someProperty,interceptor)
  • Object.intercept.afterSet(someObject,someProperty,interceptor)

You can also short circuit the interceptor chain by throwing an Error object. If you like getOwnPropertyDescriptor or defineProperty but dislike the boilerplate, then you might prefer Simon’s API.

Node Roundup: Node 0.12.1, io.js 1.6.2, DIY, Typescript-Deferred

25 Mar 2015 | By Alex Young | Comments | Tags node libraries modules iojs npm build

Node 0.12.1

Yesterday Node 0.12.1 was released. It has OpenSSL fixes for security vulnerabilities that include a DoS. Two fixes are ranked as high, and nine are marked as moderate.

io.js just hit version 1.6.2. The recent io.js releases have had tls and http fixes, but there are other very interesting changes if you dig into the changelog. For example, the Node binary can now be invoked with a list of modules to preload:

iojs -r foo -r /bar/baz.js -r quux

This is equivalent to:

require('foo');
require('/bar/baz.js');
require('quux');

The reason I like this is it means environment-specific modules can be loaded without changing your code. You could use this to load modules that instrument the runtime with debugging and logging functionality.

The npm blog (yet again) has a useful post for client-side developers: Using Angular’s new improved Browserify support:

With the recent release 1.3.14 instantaneous-browserification, Angular introduced better support for those using Browserify. Thank you to everyone who worked on that issue, and especially to Ben Clinkinbeard for his unflagging dedication in getting it in.

I prefer reading AngularJS code with CommonJS modules, so it would be cool to see AngularJS module maintainers using Browserify for modules on npm.

DIY: JavaScript that Compiles to a Makefile

DIY

I’ve used Gulp and Grunt to manage client-side builds, but as someone who used to write makefiles I’ll admit to wishing everyone just used make. Well, now maybe we can, with Vittorio Zaccaria’s DIY (GitHub: vzaccaria/diy, License: BSD, npm: diy).

Here’s a sample configuration file:

generateProject(_ => {
  _.collectSeq("all", _ => {
    _.collect("build", _ => {
      /* specify how to build files */
    })
    _.collect("deploy", _ => {
      /* specify how to deploy files */
    }
  })
})

DIY is a DSL for describing build processes. The generateProject function is used to wrap calls to various methods that describe build steps. The final makefile is generated by using babel, so you just have to type babel configure.js | node. Once you’ve got a makefile you can invoke the targets that were defined by calls to the collect method.

This module gets top marks for using Babel and for generating something that’s friendly for Unix grumps like me.

Typescript-Deferred

What if you want TypeScript-friendly promises? Typescript-Deferred (GitHub: DirtyHairy/typescript-deferred, License: MIT, npm: typescript-deferred) by Christian Speckner is a Promises/A+ implementation written in TypeScript. The author says nobody needs another promises implementation, but this implementation is pretty cool: it has no dependencies, and fully implements the specification.

If, like me, you’re a TypeScript tourist, then here’s what strongly typed promises look like:

// A promise for a number that resolves to 10
var promise: tsd.PromiseInterface<number> =
    tsd.when<number>(10);

// A promise that adopts the state of some other thenable that wraps a value
// of type sometype
var promise: tsd.PromiseInterface<number> =
    tsd.when<sometype>(someThenable);

Christian suggests that this will be useful if you want to embed a small promises implementation into your own libraries.

ASCII to Vector Images

24 Mar 2015 | By Alex Young | Comments | Tags mac es6 ascii graphics

ASCII to vector

Charles Parnot, developer of a lab notebook application for Mac OS, recently gave a talk at NSConference about turning ASCII art into vector drawings. He’s written a post about it with some awesome diagrams, entitled Replacing Photoshop With NSString:

Each shape is defined by a series of sequential characters, and a new shape is started as soon as you skip a character in the above list. So the first shape could be defined by the series ‘123456’, then the next shape with ‘89ABCDEF’, the next with ‘HIJKLMNOP’, etc. The simplest method +imageWithASCIIRepresentation:color:shouldAntialias: will draw and fill each shape with the passed color (there is also a block-based method for more options).

Earle Castledine has developed a JavaScript version called Cocoscii that can generate DOM images. The API is based around template strings:

const closeImg = cocoscii(`
  · · · · 1 1 1 · · · ·
  · · 1 · · · · · 1 · ·
  · 1 · · · · · · · 1 ·
  1 · · 2 · · · 3 · · 1
  1 · · · # · # · · · 1
  1 · · · · # · · · · 1
  1 · · · # · # · · · 1
  1 · · 3 · · · 2 · · 1
  · 1 · · · · · · · 1 ·
  · · 1 · · · · · 1 · ·
  · · · 1 1 1 1 1 · · ·
  `, (idx, style) => {
    if (idx === 0) {
      style.fill = "#000";
    } else {
      style.stroke = "#fff";
    }
  });

The readme describes how drawing with ASCII works:

The basics are, you fill a grid with the ordered markers … Any other characters are ignored.

If the numbers are sequential, they become a path. If you skip a number, then a new path starts. If a number is repeated twice, it becomes a line. If a number is repeated more than twice, it becomes a circle that fits inside the bounding box of all the points.

This sounds like a potentially hacker-friendly way of generating icons and simple game animations. I imagine it would be pretty easy to use it with effects like gradients and drop shadow.

Maybe there’s even some way of extending the principle to something like Monodraw?

Update: There’s also a Node implementation now as well! (npm: node-cocoscii)

Interdimensional, Package Quality

23 Mar 2015 | By Alex Young | Comments | Tags touchscreen mobile npm modules

Interdimensional

Interdimensional (GitHub: vodkabears/Interdimensional, License: MIT, npm: interdimensional, Bower: interdimensional) by Ilya Makarov is a library for responding to gyroscope events on devices that support the deviceorientation event. The demo site will start responding to tilts when you tap the polygon icon at the bottom-left of the screen.

The library’s behaviour can be tweaked by changing the PPD option (pixels per difference between tilts), and there’s also an insensitivity option for the minimum difference between tilts.

To start using spatial scrolling, call Interdimensional.charge. The library will emit events on the document object, so you can detect when the feature is enabled (interdimensional:charge), and if it wasn’t possible to enable it (interdimensional:fail).

Package Quality

Package Quality

Package Quality by Alex Fernández is a service that evaluates npm packages based on npm and GitHub metrics. It’s ideal if you want to quickly compare several competing packages.

The source is on GitHub (alexfernandez/package-quality) and the project is written with Express and MongoDB. The readme for the project has more details about how package quality is determined. The authors admit that any such measurements are potentially problematic, but they explain how version, downloads, and repo quality is measured so you can see what the numbers really mean.

SceneVR: Node and WebGL 3D Scenes

20 Mar 2015 | By Alex Young | Comments | Tags meteor books sponsored-content WebComponent react

SceneVR

For years I’ve wanted to make a WebGL version of Elite (or maybe Elite II). The technical trick to making it really compelling and native to the web would be if it streamed data with WebSocket to the client… maybe huge persistent galaxies could live on clusters of Node/io.js servers!

I’m never going to have the time to make anything like that, but Ben Nolan’s SceneVR project (GitHub: bnolan/scenevr, License: BSD, npm: scenevr) seems like a fun way of experimenting with interconnected virtual reality worlds. The demo allows you to walk around a 3D world with links to various games. There’s a Pac-Man game, a chess game, and some other cool stuff as well.

It works by streaming XML data to the browser from a Node server. The server uses Express, and the scenes rendered on the client use HTML-like markup with CSS:

<scene>
  <box id="mycube" position="1 2 3" scale="1 1 1" style="color: #f07" />
</scene>

The scenes can then be scripted with JavaScript, so you can add rules to create games:

document.getElementById("mycube").addEventListener("click", function(e){
  document.scene.removeChild(document.getElementById("mycube"));
});

It even supports multiplayer games by streaming player events to each client. Editing scenes also pushes data to the client, so you can live edit and quickly preview the results.

Ben has added WebVR browser support, so if you’ve got an Oculus Rift you can actually view scenes in VR.

AniCollection, SuperFetch

19 Mar 2015 | By Alex Young | Comments | Tags node modules libraries css animation http

AniCollection

I usually write CSS animations by failing to remember the syntax and then copy and pasting examples until it works the way I want. In times like that a handy directory of CSS animations is essential. AniCollection (GitHub: anicollection/anicollection, License: MIT) by Dariel Noel is big collection of CSS animations. Each animation has a preview and the associated CSS in an easy copy and pastable format.

AniCollection

The site itself is on GitHub, and the author has built it with Grunt, css-annotation, and js-beautify.

SuperFetch

I actually like the request module’s API, but juggling multiple requests can be awkward. SuperFetch (GitHub: luin/superfetch, License: MIT, npm: superfetch) by Zihua Li is a promise-based HTTP API that is built on request:

var fetch = require('superfetch');
fetch.get('http://example.com').then(function(body) {
  // when the status code begins with "2", the response body will be returned.
}).catch(function(response) {
  // otherwise, the whole response(including headers) is returned.
});

You can use fetch.get.option to set options, and you can chain calls to option if you like. The request and response objects can be transformed with callbacks, and the author has included unit tests written with Mocha.

Node Roundup: 0.10.37 and io.js 1.5.1, Node and Real-time Finance, comws

18 Mar 2015 | By Alex Young | Comments | Tags node modules libraries generators articles

0.10.37 and io.js 1.5.1

Node 0.10.37 was released on Saturday. This updates uv, domains, buffer, console, v8, and http. The uv update fixes a security issue which allowed attackers to gain elevated privileges due to the way setuid and setgid were used.

io.js 1.5.1 also came out last week. The blog post has some useful community updates, including a talk by Tony Pujals about the future of io.js.

There’s also an npm weekly post about fixes for npm shrinkwrap --dev, changes to shrinkwrap in npm 3, and a screencast by Ben Clinkinbeard about using npm link.

Node and Real-time Finance

Imre Fazekas sent in two articles about Node and real-time finance:

The first part covers the background and architecture of the project, and the second part goes into the build system. It sounds like the third part will expand on client/server code sharing, so presumably it’ll feature some of the author’s experiences with isomorphic templates and view models.

Comws

What if you like Koa’s generator-based middleware but don’t want to use Koa? Andrea Parodi has created Comws (GitHub: shes/comws, License: MIT, npm: comws), a library based on co that you can use with any Node application.

To use it, create an instance of CoMws and then add generators to the middleware stack:

var CoMws = require('comws');
var mws = new CoMws();

mws.use(function *(next){
  this.result += ' hello';
  yield next();
});

mws.use(function *(next){
  this.result += ' world';
  yield next();
});

var ctx = { result: 'yet another' };

mws.run(ctx).then(function() {
  //ctx.result === 'yet another hello world' 
});

If you’re using Node 0.11.x or 0.12.x you’ll need to run node with --harmony-generators or --harmony, but io.js should work without the flags.

I’d like to try this with Express, but it also seems like a useful module for non-web Node programs.

Logdown: Generate Logs with Markdown

17 Mar 2015 | By Alex Young | Comments | Tags libraries modules console logging

A few years ago, Firefox and Chrome added support for styles to log messages. This means you can call console.log with an additional CSS option. I’ve noticed a few libraries and frameworks using this to good effect for debugging messages, but an idea that’s new to me is combining Markdown with logging.

Logdown (GitHub: caiogondim/logdown, License: MIT, npm: logdown) by Caio Gondim is a module that lets you include Markdown in logs for both the browser and server. It can do the basics, like italic and bold, but the thing that I really like is including code.

To use it, instantiate a new Logdown instance, and then just log as you would with console.log:

var Logdown = require('logdown');
var debug = new Logdown({ prefix: 'foo' });

debug.log('lorem *ipsum*');
debug.info('dolor _sit_ amet');
debug.warn('consectetur `adipiscing` elit');

The module supports various options: you can turn off Markdown parsing and add a prefix. It supports Node 0.10+, io.js 1.0+; and Chrome, Firefox, IE 9+, Opera, and Safari 8.0+.

StringFormatter, Hapi.js in Action, FullStack 2015

16 Mar 2015 | By Alex Young | Comments | Tags libraries strings books conferences events

StringFormatter

Simon Blackwell sent me StringFormatter (GitHub: anywhichway/stringformatter, License: MIT), a string formatting library that aims to go beyond the new ECMAScript string templates. It’s a bit like sprintf formatting, but includes some more complex features:

  • Numerical type formatting
  • Date formatting
  • CSS styles
  • Conditional formatting
  • Caching

It can handle expressions like currency as well, which is ideal for web applications when you want to display multiple currency formats. You can use StringFormatter.register to register a formatting for a type. For example, if you had a date formatter object you could associate it with Date like this: StringFormatter.register(Date, dateFormatter, 'Date').

The usual way to format a string is with StringFormatter.format, but you can use StringFormatter.polyfill() to add string formatting to the String object. Format strings are represented with JavaScript-inspired syntax:

StringFormatter.format(
  "The time is now {Date: {format:'hh:mm'}} and I have {number: {fixed: 2, currency: '$'}}.",
  new Date('2015-03-13T10:01:27.284Z'),
  50.25
);

All format options accept an additional style string, which causes the output to be wrapped in span elements with inline styles.

Ideally this library should be used with a templating system to really cut down on format invocation boilerplate. Simon has included an example for the Ractive template engine.

Hapi.js in Action

Hapi in Action

Hapi.js in Action by Matt Harrison is a book that’s dedicated to web development with Hapi.js. It has been released as an early access edition, and pricing starts at $35.99 for the eBook. The planned content includes authentication, building modular applications with plugins, testing, production, proxies, and creating streaming services.

Hapi.js in Action teaches you how to build modern Node-driven applications using Hapi.js. Packed with examples, this book takes you from your first simple server through the skills you’ll need to build a complete application. In it, you’ll learn how to build websites and APIs, implement caching, authentication, validation, error handling, and a lot more. You’ll also explore vital techniques for production applications, such as testing, monitoring, error handling, deployment, and documentation.

The first chapter is available for free, and early access supporters can get chapters two and three as well.

FullStack 2015

FullStack 2015 is an event that’s all about JavaScript, Node, and the Internet of Things, that will be held in London on 25th to 27th June. Tickets start at £375 for early bird tickets.

There’s currently a FullStack call for papers, so if you’re interested in speaking at the conference you’ve got a week to apply.

Prüfer, Calendar Base

13 Mar 2015 | By Alex Young | Comments | Tags dom modules node testing calendar

Prüfer

Johnathan Leppert wanted a way to generate complex DOM structures for UI performance testing. He decided to use the Prüfer sequence, and created a Node module that can generate random trees of data (GitHub: jleppert/prufer, License: MIT).

Here’s an example of the usage:

var prufer = require('prufer');

// to make a tree, supply a series of integers
var tree = prufer([3, 3, 3, 4]);

// you'll get back an array of edges
console.log(tree);

I thought the Prüfer sequence sounded like a cool way to do this – it might be useful for lots of Node-related stream tools.

Calendar Base

Wesley de Souza sent in a module for generating calendars as arrays of objects. The module is called Calendar Base (GitHub: WesleydeSouza/calendar-base, License: MIT, npm: calendar-base). To use it, you just need to instantiate a new calendar:

var cal = new Calendar({ siblingMonths: true });
cal.getCalendar(2015, 5);

The arrays it generates have objects like this: { day: 31, weekDay: 0, month: 4, year: 2015, siblingMonth: true }. It also has methods for changing the start date, and selecting the current date.

It reminds me of typing cal in Unix, which is still how I use calendars instead of using a fancy desktop application…

Your First Meteor Application, CommonJS React Components, WebComponents

12 Mar 2015 | By Alex Young | Comments | Tags meteor books sponsored-content WebComponent react

Your First Meteor Application

Your First Meteor Application

David Turnbull sent me Your First Meteor Application, a highly focused, beginner-friendly introduction to Meteor. One thing that’s cool about this is book is David updates it regularly when Meteor changes.

You can read the book online or download the PDF for free. There are even screencasts!

CommonJS React Components

What do you do if you want to create reusable isomorphic CommonJS React components? You can install React with npm, but what’s the ideal pattern for structuring these components? How should the CSS be managed?

Aaron Kaka has been working on an experiment to use CommonJS modules as a way of sharing UI components. The work is inspired by a blog post by Simon Smith, and you can find it on GitHub here: aaronkaka/commonjs-react-components.

This proof-of-concept uses events for all interactions, so knowledge of the internal library and its dependencies is not required. You can use styling through require statements – component specific styling is scoped to the component.

It uses webpack and live reload, so it should fit in with a modern Node-based toolchain.

Using CommonJS modules and events should appeal to Node programmers who want to make reusable client-side components. If you’re a little lost with React in Node, or CommonJS and React, then this repository will give you a head start.

WebComponents

Interest in WebComponents is growing, but unless you’re involved with them it can be hard to see the benefits. Leon Revill has been working with them, and has written an article that outlines the basics of how to create WebComponents and why they’re exciting. From What are WebComponents and why are they important?:

Once WebComponents are properly supported and established you should be able to write a WebComponent that can be used in all of your projects regardless of the other technologies used. Forget writing plugins for jQuery, directives for AngularJS and addons for Ember.js. Write once use many. This has a huge benefit and in my mind is one of the most significant benefits of WebComponents.

The article includes technical examples and addresses some concerns about the divergence between X-Tag, Polymer and Bosonic.

Node Roundup: io.js, npm and jQuery, error-system

11 Mar 2015 | By Alex Young | Comments | Tags node modules libraries error-handling iojs hardware

io.js

Last Friday, io.js 1.5.0 was released, which is another major milestone for the project. It introduces a new Buffer.prototype.indexOf method, which is like Array.prototype.indexOf. This is implemented in node_buffer.cc, and works with strings and numbers.

Last week Rodd Vagg posted a comment about io.js on DailyJS to say that the ARMv8 support is separate to the earlier Node support for ARMv6 and 7, and it actually sounds quite significant. According to last week’s release notes, Linaro has contributed hardware to help io.js with ARMv8:

this is an entirely new architecture from ARM that adds 64-bit support which they are heavily pursuing the server market with. io.js (Node) + ARMv8 on the server is an amazing opportunity and ARM have been lending their support to the io.js project to make this work.

64bit ARM means more RAM in Android phones and tablets, which is great. But what about servers – are we going to be able to use low-powered clusters of powerful ARM machines? Linaro has details on its ARM servers, and has an application form for people to request access to try them out. Linaro says it’s planning to use servers are based on Opteron A1100 Cortex-A57, and X-Gene.

The best place to read more about the latest io.js release is the io.js Week of March 6th post on Medium. Which reminds me, there’s an @iojs Medium account which is definitely worth following.

npm and jQuery

The npm weekly update points to yet another npm and jQuery plugin article. This one talks about how to make your own jQuery plugins make better use of npm. This includes referencing stylesheets in package.json and CommonJS compatibility.

error-system

Something I like to do in my Node-based web apps is include an errors.js file that subclasses Error with constructors named after HTTP errors. It makes it easier for me to pass the right error into next (in Express/Connect) so the error gets passed along to a centralised error handler. The way I do it is basic old skool JavaScript, so I’ve been looking for ways to improve it

Fomichev Kirill noticed Rod Vagg created node-errno. Rodd’s module includes errors for libuv and Node, so you can check error codes with expressions like require('errno').code.ENOTEMPTY. You can also use it as a command-line tool for checking Node errors, and it has an API for making custom errors. The custom errors include the call stack, and it allows error hierarchies to be created.

Inspired by this, Fomichev made error-system (GitHub: fanatid/error-system, License: MIT, npm: error-system). It’s similar to Rodd’s module, but is designed specifically for creating custom errors. If you were making a web application, you could make a class for request errors like this:

var errorSystem = require('error-system')
var RequestError = errorSystem.createError('RequestError', 'Code: {0} (url: {1})')

This is exactly what I wanted when I made my original errors.js file. I particularly like the numbered arguments in Fomichev’s module because it cuts down the amount of boilerplate when compared to my solution.

Slideout.js, Shipit vs Flightplan

10 Mar 2015 | By Alex Young | Comments | Tags deployment articles ui libraries

Slideout.js

Slideout.js (GitHub: mango/slideout, License: MIT, npm: slideout) by Guille Paz is a touch-based slideout navigation menu for mobile applications. It doesn’t use any dependencies, and the markup is sensible. It has CSS transforms and transitions, and uses native scrolling.

The markup is based on HTML5 tags, so you can define the navigation panel with a nav element. It works in most browsers, and the base version of IE is 10.

The JavaScript API uses a Slideout constructor function, and it accepts options for animations, duration, and the necessary DOM elements.

One nice thing about this library is there are lots of ways to install it: npm, spm, bower, and component are all supported.

Shipit vs Flightplan

I’ve written about Shipit and Flightplan, but I haven’t yet used both deployment solutions for anything serious. John Munsch has written a long post about his experiences using both Shipit and Flightplan with a DigitalOcean server:

I did everything from start to finish myself and I felt duly proud about having built something from scratch and launched it no matter how small it was. The tasks covered by my scripts were: initial machine configuration, updating of Ubuntu (mainly to get security fixes), deployment, and creating a SSH shell to the remote server.

Using a cheap VM can be very affordable if you want to host your own email, web services, and maybe use it for IRC. Deployment is naturally more work than something like Heroku, but Shipit and Flightplan can really streamline things.

John’s article compares the pros and cons of each library, and he’s included the scripts he used for deployment.

Motion Sensing with the Doppler Effect

09 Mar 2015 | By Alex Young | Comments | Tags experiments motion

If you try out the following project, be aware that it emits a high frequency sound! Daniel Rapp, who previously sent in Spectroface, has been working on motion sensing using the Doppler effect (GitHub: DanielRapp/doppler, License: MIT). It’s based on a paper (PDF: guptasoundwavechi2012.pdf) that explores the concept in more detail. From the abstract:

We present SoundWave, a technique that leverages the speaker and microphone already embedded in most commodity devices to sense in-air gestures around the device. To do this, we generate an inaudible tone, which gets frequency-shifted when it reflects off moving objects like the hand. We measure this shift with the microphone to infer various gestures. In this note, we describe the phenomena and detection algorithm, demonstrate a variety of gestures, and present an informal evaluation on the robustness of this approach across different devices and people.

Daniel’s version uses HTML5 and includes several examples, including page scrolling and a theremin. The source uses the audio API and typed arrays. I haven’t fully figured out the source, but I think it emits tones from the left and right speakers and then compares the result from the mic to figure out movement.

This is one of the best hacks I’ve seen for a while, and although the tone makes the applications limited the fact it works at all is fascinating!

Angular 2 and TypeScript, Comparing Angular 1.x and 2.0

06 Mar 2015 | By Alex Young | Comments | Tags angular typescript

Angular 2 is Built on TypeScript

There’s a post on the msdn blog that says Angular 2.0 is built with TypeScript. This is a big step, but there is a precedent for it – an earlier Angular blog post mentioned the AtScript project that resulted in a collaboration between Microsoft and the Angular team.

This partnership has been very productive and rewarding experience for us, and as part of this collaboration, we’re happy to announce that Angular 2 will now be built with TypeScript. We’re looking forward to seeing what people will be able to do with these new tools and continuing to work with the Angular team to improve the experience for Angular developers.

Now AtScript development has been abandoned in favour of TypeScript, what does this mean for Angular developers? There’s a TodoMVC TypeScript Angular 2.0 example project on GitHub, which uses JavaScript for the main code. To use it, you’ll need to download the new Angular 2.0 code separately.

Hopefully this shift will result in a more future-proof Angular, but it’s hard to tell if switching to TypeScript now is a good idea, given the interest in ES6 and ES7.

Comparing Angular 1.x and 2.0

In case you’re excited/worried/apathetic about the previous news, Shawn McKay sent in a post that compares angular 2.0 with 1.x:

Angular 2.0 looks fantastic. It’s not ready yet, but you can play around with it today. Checkout the GitHub for more. There are also some examples available, such as ng2do.

The post explains how to set up Angular 2.0 and outlines the major new features. If you’re also working with React, then you might want to read more about the new DOM handling:

“2.0: In many ways, Angular 2.0 seems to handle DOM style manipulation with something similar to React.js’s virtual DOM, which they referred to in a recent presentation as the “view”. In response to a recent question about ‘Angular Native?’, Misko mentioned that this View could be run on a web worker or even potentially on native.”

Make Parsers and DSLs with Jacob

05 Mar 2015 | By Alex Young | Comments | Tags node modules libraries browser parsers lexers

Recently there have been several exciting projects that provide support for upcoming ES6 and ES7 features. One way of implementing parsers like this is with a context-free grammar. A popular way to do this is with Jison, but Gabriele Cannata sent in a new library called Jacob (GitHub: Canna71/Jacob, License: ISC, npm: jacob).

Jacob has a lexer and a parser. In that sense it’s inspired by both Flex and Bison. If you want to learn about Flex and Bison, I found an article about writing a toy compiler with Flex, Bison, and LLVM. Jacob’s lexer supports regular expressions and lexer actions. The parser supports simple LR parsing, Look-Ahead LR parsing, and canonical LR parsing. The grammar is specified with Extended Backus–Naur Form, which means you define a formal language based on how symbols can be combined into legal sequences.

This means you can define your language or DSL, validate code written with it, and produce abstract syntax trees that can be used to write compilers.

I’ve written very basic grammar files with Jison before, and I’ve found that it takes practice to get the hang of it. The best place to get started is with real examples, so have a look at the Jacob examples folder. Also, the JSON definition on the json.org site will help you to understand how something you’re familiar with maps to a formal grammar.

If you’ve ever wondered how people write things like transpilers in a formal and structured way, then it’s worth checking out Jison and Jacob.

Node Roundup: npm 3, io.js 1.4.3, NoDent

04 Mar 2015 | By Alex Young | Comments | Tags node modules libraries iojs npm async

npm: Roadmap for 3, Using jQuery Modules

The npm roadmap has been updated with details on npm. This includes multi-stage installation, improvements to shrinkwrap, and progress bars. There’s an entry that aims to solve the front-end tooling problem, and I noticed shipping HTML and CSS is mentioned. I prefer a Browserify/npm-based workflow, but I’ve always found this stage less than elegant, so it’ll be interesting to see what happens there.

To read more, visit the npm blog. There’s also another interesting post about jQuery, which describes how to use jQuery plugins through npm. The previous post on jQuery was about publishing modules, but this one shows how to consume plugins even if they don’t use npm.

io.js 1.4.3

There was a new io.js release (1.4.3) on Monday, which has quite a big fix for streams on Windows and the beginnings of ARM support. The 1.4.x branch was released at 1.4.1 due to a libuv bug in 1.4.0. This branch adds newer versions of V8, npm, and libuv, but also has improvements for process, stream, and http.

For more details on io.js and npm changes, you can look at the changelogs on GitHub:

They’re both nicely annotated with links to commits, and summarise major changes.

NoDent

In my DailyJS email backlog I found NoDent (GitHub: MatAtBread/nodent, License: BSD-2-Clause, npm: nodent). It’s a small module that adds support for the proposed aysnc and await keywords. They’re not too hard to learn, and once you get used to them they can make asynchronous code more readable.

The basic idea is to mark asynchronous functions with the async keyword, and then use the await keyword before they’re called.

async function tellYouLater(sayWhat) {
  // Do something asynchronous and terminal, such as DB access, web access, etc.
  return result;
}

var result = await tellYouLater('Hi there');

This will cause execution to wait until tellYouLater returns. I’ve used async/await in C#, and it works well for methods that return a single value (rather than an observable with a sequence of values).

The author’s readme has lots of examples of uses and abuses, so it’s worth reading if you seriously want async/await now.