08. October 2015

Generator Nom

generator-nom (GitHub: ironSource/node-generator-nom, License: MIT, npm: generator-nom)

We all strive to write DRY code, but still while setting up projects and maintaining depenencies we are constantly repeating ourselves. I find myself going through the same flow time and time again. git init, npm init, touch README.md, going to Github getting an origin to push to et cetra. This process is a pain every time. What if you could just generate all this stuff with one command.

That is where the yo nom come in. Nom is a Yeoman generator which is a collection of several sub-generators. It includes the following generators;

npm

Create package.json and prompt to keep dependencies of a previous package.json if any. Create .gitignore, cli.js (optional), install test framework (tape, tap, mocha, grunt, cake, or ava), add LICENSE file (MIT, BSD2 or BSD3).

git

Initialize local git repository, unless .git directory exists

github

Create public or private GitHub project, named “module-name” or “node-module-name”, unless local git already has configured remotes. Asks for access token and repository owner (which defaults to the owner of the token), skips creation if the repository already exists, adds URLs to package.json and adds remote origin.

travis

Add .travis.yml for node 0.10 and iojs, setup GitHub hook. The travis tool asks for username and password.

appveyor

Add appveyor.yml for node 0.10 and iojs, setup GitHub hook. Asks for access token.

gulp

Create an ES6 gulpfile and tasks directory.

style (still to come)

Add standard or xo as a pretest script

readme

Add readme.md with common sections and shield.io badges for npm and david. If you did the travis and/or appveyor setup, badges for those services will be added as well.

To use a specific generator you can select it like this:

yo nom:<generator>

To run them all use:

yo nom:*

That’s it.

I’ve tried this out and will probably be using this to make my workflow a bit more DRY and hope that other people will also consider to optimize their workflow with modules like nom.

07. October 2015

Read file relative

read-file-relative (GitHub: inikulin/read-file-relative, License: Unknown, npm: read-file-relative)

A problem everybody probably encounters once in a while is relativity of file paths while reading files with Node.js. You would do something like this:

var fs   = require('fs');
var path = require('path');
var data = fs.readFileSync(path.join(__dirname, '/data-file.txt')).toString();

// Or like:
var fs   = require('fs');
var data = fs.readFileSync(__dirname + '/data-file.txt').toString();

// Or even like this
var fs   = require('fs');
var data = fs.readFileSync('./data-file.txt').toString();

Now you can easily read out files without all the annoying boilerplate code. Imagine a world where you could do this:

var data = readSync('/data-file.txt');

Well you can stop imagining, because it’s here and it’s called read-file-relative. Read-file-relative comes with two main functions on it’s API: read and readSync. Let’s take a look.

To read out the file synchronously this is what you would do.

var readSync = require('read-file-relative').readSync;
var data = readSync('/file.txt');

When you prefer asynchronously reading you just provide a callback like this:

var read = require('read-file-relative').read;
read('/file.txt', 'utf8',function(err, content) {
   // ...
});

Note that for the read we need to provide the encoding else it will return a buffer.

Besides reading files you can also just convert a path to an absolute path like this:

var toAbsPath = require('read-file-relative').toAbsPath;
var absPath = toAbsPath('/file.txt');

This is a nice addition to everybody’s toolbox. It doesn’t do much, but what it does, it does very well.

06. October 2015

Speck JS

SpeckJS (GitHub: speckjs/speckjs, License: MIT, npm: speckjs)

SpeckJS is a library that parses JavaScript comments and outputs unit-tests. SpeckJS currently supports Tape, Jasmine, and Mocha/Chai.

SpeckJS comes with plugins for Grunt, Gulp and Atom.

The goal of SpeckJS is to make it as easy as possible to get started using Test-Driven Development on a new project or to quickly add unit-tests to your existing project.

Let’s make a test.

/*
test > sum function
# sum(1, 2) == 3 (returns the sum of both params)
# sum(3, 4) == 7 (returns the sum of both params)
*/

function sum(a, b){
    return a + b;
}

SpeckJS supports some basic assertion like: equal, strict equal, not equal. Besides relying on all the tools already provided, such as gulp and atom plugins, you could also script yourself with the API like this:

var speck = require('speckjs');

// file object to be passed as an argument
var file = {
  name: 'demo.js',
  content: scriptContent
};

// options hash selecting Jasmine and specifying a callback
var option = {
  testFW: 'jasmine',
  onBuild: function(data) {
    console.log(data);
  }
}

// Returns Jasmine test file
var result = speck.build(file, option);

We will start using this in my company from now on, because it makes it a lot easier to integrate testing in a long running project that has never being tested just by walking through the files. I hope to see other people pick this up aswel.

05. October 2015

Velocity React

velocity-react (GitHub: twitter-fabric/velocity-react, License: MIT, npm: velocity-react)

Today I had some trouble finding something to write about. Then I remembered the awesome work done by the guys at Twitter Fabric. They made a React component for interacting with amazing Velocity animation library. Offical introduction can be found here.

If you are not familiar with Velocity I suggest you take a look at this first.

The package contains two components; <VelocityComponent /> and <VelocityTransitionGroup />

Velocity React integration follow this simple algorithm:

  • Initially, an animated component will appear as it would at the end of its given animation.
  • If that given animation ever changes, it runs it to get to the new end state. If there’s an animation currently in progress, we stop it first, and then proceed smoothly from whatever intermediate state it left us in.

Here is a small example that was given in the introduction from Fabric.

render: function () {
  var animationProps;
  if (this.state.hovering) {
    animationProps = {
      duration: 200,
      animation: {
        rotateX: 160
      }
    };
  } else {
    animationProps = {
      duration: 1100, // longer due to swinging
      animation: {
        rotateX: [0, 'spring']
      }
    };
  }

  return (
    <div onMouseEnter={function () { this.setState({hovering: true}); }}
         onMouseLeave={function () { this.setState({hovering: false}); }}>
      <VelocityComponent {...animationProps}>
        {this.renderTopState()}
      </VelocityComponent>
      {this.renderUnderneathStats()}
    </div>
  );
}

Which will result in:

As the name implies <VelocityTransitionGroup /> can be used to animate a group of element at the same time. In the example on the Fabric blog we can use it being used to animate an input slider, but that’s not all. When you pay close attention you will the the toggle switch animating and a “jawbone” collapse. Al these animation are done at once.

I was very impressed with the work and I’m trying to push this as the new standard for animating React components at the company where I work. And will be the default for all my pet projects.

02. October 2015

Scroller Friday

fartscroll.js (GitHub: theonion/fartscroll.js, License: MIT)

Since it is Friday today my colleages and me are in a humorous mood. So when I started looking what to write about today I got some real fun suggestions. The first one is fartscroll.js.

The name already saids it all, it’s a library that makes your page fart when the user is scrolling. Because everybody farts and likes farting, why not give your application the same privilege? Here is how:

First we need to include the script within our markup.

<script src="http://code.onion.com/fartscroll.js"></script>

Then we call it like this:

// Fart every 400 pixels scrolled in the window
fartscroll();

When you think you pages farts to often you can increase the amount of pixels that need to be scrolled before farting like this:

// Fart every 800 pixels scrolled in the window
fartscroll(800);

If you just want to have some fun on other webpages, you can use this bookmarklet. Here is the code for it.

javascript:%20(function%20()%20{%20%20%20%20%20var%20fs%20=%20document.createElement('script');%20%20%20%20%20fs.setAttribute('src',%20'http://code.onion.com/fartscroll.js');%20%20%20%20%20document.head.appendChild(fs);%20%20%20%20%20window.setTimeout(function(){%20%20%20%20%20%20%20%20%20fartscroll(800);%20%20%20%20%20%20%20%20%20},%20500);%20}());

Elevator.js

elevator.js (GitHub: tholman/elevator.js, License: MIT)

While we are in the theme of scrolling libraries, here is another fun one. I cannot say that this one is very new, but it’s still gold in my opinion. So what does it do? Elevator.js is provides you with a “back to top” button that behaves like a real elevator. Now your users don’t have to be bored during the awkward time they spend waiting for your page to scroll back to the top. How do we use this?

First we need to include the script within our markup.

<script src="https://cdn.rawgit.com/tholman/elevator.js/master/elevator.min.js"></script>

Now we need to instantiate it with some mp3 files and a trigger target like this:

window.onload = function() {
  var elevator = new Elevator({
    element: document.querySelector('.elevator-button'),
    mainAudio: '/src/to/audio.mp3',
    endAudio: '/src/to/end-audio.mp3'
  });
}

If you do not have any inspiration for sounds you can just use the defaults like this:

window.onload = function() {
  var elevator = new Elevator({
    element: document.querySelector('.elevator-button'),
    duration: 1000 // milliseconds
  });
}