DailyJS

DailyJS

The JavaScript blog.


Tagwebsockets
Featured

libraries browser modules websockets authentication angular

angular-oauth2, angular-websocket

Posted on .

angular-oauth2

angular-oauth2 (GitHub: seegno/angular-oauth2, License: MIT, npm: angular-oauth2, Bower: angular-oauth2) by Rui Silva at Seegno is an AngularJS OAuth2 client module that uses ES6 internally. The author has kindly released it on npm and Bower, so it should be easy to quickly try it out.

To use it, you have to configure OAuthProvider with the server's base URL, and then the client ID and secret. Then you can request access and refresh tokens as required. The error handling is nice because you can hook into error events on $rootScope.$on('oauth:error'.

I've written a few browser extensions that use OAuth, and this seems ideal for that kind of work. It will also be useful for your Angular single page web apps.

angular-websocket

PatrickJS (Patrick Stapleton) sent in angular-websocket (GitHub: gdi2290/angular-websocket, License: MIT, npm: angular-websocket, Bower: angular-websocket), which is a WebSocket library for AngularJS 1.x. It works by providing a factory, $websocket, that you can use to stream data between the server and your Angular app.

The API is modeled around the standard WebSocket API:

angular.module('YOUR_APP', [  
  'ngWebSocket' // you may also use 'angular-websocket' if you prefer
])
//                          WebSocket works as well
.factory('MyData', function($websocket) {
  // Open a WebSocket connection
  var dataStream = $websocket('wss://website.com/data');

  var collection = [];

  dataStream.onMessage(function(message.data) {
    collection.push(JSON.parse(message.data));
  });

  var methods = {
    collection: collection,
    get: function() {
      dataStream.send(JSON.stringify({ action: 'get' }));
    }
  };

  return methods;
})
.controller('SomeController', function(MyData) {
  $scope.MyData = MyData;
});

In this example you would use MyData in the corresponding markup. Patrick's example uses ng-repeat to iterate over the data.

The project includes browser tests and a build script. It doesn't have any fallback for browsers that don't support WebSockets, so it's a pure WebSocket module rather than something like Socket.IO.

Featured

node npm websockets

Socket.IO Debugging

Posted on .

How do you debug WebSockets, other than inserting console.log all over the place? One technique is to look at the Frames tab, under Network, in WebKit Inspector.

The Frames tab in WebKit Inspector.

The term "frames" refers to the data that is sent in a WebSocket connection. Unfortunately, I've been doing some work with WebSockets inside a desktop application, so I can't easily see WebKit inspector.

Diego Costantino sent in ThreePin (GitHub: dieguitoweb / ThreePin, License: MIT, npm: threepin, bower: dieguitoweb/ThreePin), a tool for developing and testing software that uses Socket.IO and Node:

ThreePinJS is a stress-free test environment for Socket.IO allows you to test your WebSocket server code before you write the client code.

It uses a configuration file called threepin.json that sets up a server, and a list of events to listen for and send. The readme has a full example.

Once the server is configured, you can use any local HTTP server you want to serve a simple HTML file that connects and runs through the event list. It means you can focus on the server-side logic before worrying about the client-side code.

I'm still looking for options to help test and debug Socket.IO projects, but I thought ThreePin was an interesting stab at the problem.

Featured

testing node modules websockets mocha crawling

Node Roundup: 0.8.14 and 0.9.3, Orange Mocha Frappuccino, Crawlme, WebSocketIPC

Posted on .

You can send in your Node projects for review through our contact form or @dailyjs.

0.8.14 and 0.9.3

Last week, 0.8.14 and 0.9.3 were released. The 0.8.14 release is basically the 0.8.13 release with a fix for EventEmitter:

Note: v0.8.13 contains a regression in the EventEmitter class. This is a bugfix release, but contains no new features. Most of the release notes are copied from v0.8.13, since it didn't live long.

The 0.9 release updates V8 and has various bug fixes. It also adds an options argument to util.inspect -- the older API had three arguments, so reducing the arity makes sense as new options can be supported more easily.

Orange Mocha Frappuccino

Orange Mocha Frappuccino (License: MIT, npm: omf) by Brian Carlson is a library to help build HTTP verification tests with Mocha. It can accept a Node HTTP server or URLs:

var omf = require('omf');  
var assert = require('assert');

omf('https://github.com', function(client) {  
  client.get('/brianc/node-omf', function(response){
    response.has.statusCode(200);
    response.has.body('ORANGE MOCHA FRAPPUCCINO');

    //the full response is available to any custom tests:
    it('has ETag header', function() {
      assert(this.response.headers['etag']).ok();
    });
  });
});

This is a little bit more like how Expresso worked, which was TJ's pre-Mocha test framework.

Crawlme

Crawlme (License: MIT, npm: crawlme) from Optimal Bits is Connect middleware for automatically mapping hashbang URLs to parameter-based URLs for Googlebot Ajax Crawling.

WebSocketIPC

WebSocketIPC (License: GPL) by Nicolas Froidure is a proof-of-concept of his VarStream "variable exchange format". This format is designed to be human readable, streamable, and self-referencial.

WebSocketIPC uses WebSockets to synchronise a variable tree between multiple clients and a server. It can also synchronise data between multiple Node instances by piping VarStreams.

It's interesting that as interest in using streams grows more diverse projects are appearing to better exploit their properties.

Featured

graphics node modules websockets binary

Node Roundup: BinaryJS, Advice, Buildify, MaDGe

Posted on .

You can send in your Node projects for review through our contact form or @dailyjs.

BinaryJS

BinaryJS (GitHub: binaryjs / binaryjs, License: MIT, npm: binaryjs) by Eric Zhang uses WebSocket to stream binary data. The streams can be bidirectional, and is binary end-to-end. This basically gives browsers something closer to TCP sockets, and allows multimedia data to be streamed.

The client-side portion works with Chrome, Firefox, Internet Explorer 10, and Safari's nightly builds. The authors are working on supporting older browsers (presumably through Flash).

BinaryJS employs BinaryPack a modified version of the MessagePack protocol. The Node.js server uses a modified version of the ws library enhanced to pass through the status of the socket buffer so adherence to Node.js Stream API is possible.

Advice Functional Mixin

Advice (License: MIT, npm: advice) by Martin Angers is inspired by Angus Croll's functional mixin example. It can be used to modify an object with after, before, and around methods:

var myObj = { fn: function() {} }  
  , withAdvice = require('advice');

withAdvice.call(myObj)  
myObj.before(fn, function() {  
  // Things that should happen before fn
});

// the 'before' method will now run automatically
myObj.fn();  

The author has kindly included thorough Mocha tests as well.

Buildify

Buildify (License: MIT, npm: buildify) by Charles Davison is a build script API:

var buildify = require('buildify');

buildify()  
  .load('base.js')
  .concat(['part1.js', 'part2.js'])
  .wrap('../lib/template.js', { version: '1.0' })
  .save('../distribution/output.js')
  .uglify()
  .save('../distribution/output.min.js');

MaDGe

MaDGe (License: MIT, npm: madge) by Patrik Henningsson generates graphs based on CommonJS or AMD dependencies. It can generate various output including text-based lists in the console, and PNGs using Graphviz. There are lots of commnad-line options, which can be loaded from a JSON file.

This example shows the result of using MaDGe with Express:

MaDGe/Express

Featured

libraries node modules websockets

Node Roundup: NodObjC, SockJS, French Node Blog

Posted on .

You can send your node modules and articles in for review through our [contact form](/contact.html) or [@dailyjs](http://twitter.com/dailyjs).

NodObjC

NodObjC (npm: NodObjC) by Nathan Rajlich is an Objective-C bridge:

It uses the BridgeSupport files to dynamically generate an API from an Objective-C "Framework", and uses node-ffi to dynamically interact with the Objective-C runtime.

If you're an Objective-C developer, then you should be able to follow
this basic app structure:

var $ = require('NodObjC')

// First you need to "import" the Framework
$.import('Foundation')

// Setup the recommended NSAutoreleasePool instance
var pool = $.NSAutoreleasePool('alloc')('init')

// NSStrings and JavaScript Strings are distinct objects, you must create an
// NSString from a JS String when an Objective-C class method requires one.
var string = $.NSString('stringWithUTF8String', 'Hello Objective-C World!')

// Print out the contents (calling [string description])
console.log(string)
//   → Prints "Hello Objective-C World!"

pool('drain')

Sending messages to objects looks like this: obj('func',
arg)
. So a call like [array insertObject:obj
atIndex:5];
would be written as array('insertObject', obj,
'atIndex', 5)
.

This means Apple's native APIs are accessible from Node, so you could
create GUI apps for Mac OS. There are examples out there of GUI code
already: cocoa-hello-world2.js.

SockJS

SockJS (License: MIT) is a WebSocket emulation library that attempts to provide simple APIs for
both server and clients, while remaining as close to the WebSocket API
as possible. It's designed to work from behind restrictive corporate
proxies, and browsers that don't support WebSocket. The project includes
the server-side library,
sockjs-node and client-side: sockjs-client.

Using sockets in the browser looks like this:

var sockjs = new SockJS('http://mydomain.com/my_prefix');
sockjs.onopen = function() {
  console.log('open', e.data);
};
sockjs.onmessage = function(e) {
  console.log('message', e.data);
};
sockjs.onclose = function(e) {
  console.log('close', e.data);
};

To me this looks like the current draft of the WebSocket spec (Editor's
Draft 10 September 2011):

var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function() {
  setInterval(function() {
    if (socket.bufferedAmount == 0)
      socket.send(getUpdateData());
  }, 50);
};

This is different to Socket.IO:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

There's a detailed article about the library on RabbitMQ's blog: SockJS
- WebSocket emulation

and it includes details on how SockJS can be used with load balancing.

One interesting detail I noticed in the project README is it falls over
to polling rather than Flash:

No Flash inside (no need to open port 843 - which doesn't work through proxies, no need to host 'crossdomain.xml', no need to wait for 3 seconds in order to detect problems)

French Node Blog

Vincent Rabah emailed us to share his French Node blog: IT Wars: Node
articles
. He's got articles
covering Socket.IO, Twitter, Vim, Windows, and a variety of other topics
including log monitoring.