Art by James Halliday.

1. We run the browsers on our servers.
2. You use the browsers from the graphical web console.
3. If the servers are full, you wait in the queue.

Try Browserling!

This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->

node logoHello everyone! This is the 15th post in the node.js modules you should know about article series.

The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library, the sixth was about read - easy reading from stdin, the seventh was about ntwitter - twitter api for node, the eighth was about socket.io that makes websockets and realtime possible in all browsers, the ninth was about redis - the best redis client API library for node, the tenth was on express - an insanely small and fast web framework for node, the eleventh was semver - a node module that takes care of versioning, the twelfth was cradle - a high-level, caching, CouchDB client for node, the thirteenth was jsonstream - streaming JSON parsing library, the fourteenth was about everyauth - a module for authenticating your webapp with facebook, twitter, etc.

Today I'm gonna introduce you to procstreams by Marco Rogers aka polotek. Procstreams is a little experiment with shell scripting in node. Here is an example:

var $p = require('procstreams');

$p('cat lines.txt').pipe('wc -l')
  .data(function(stdout, stderr) {
      console.log(stdout); // prints number of lines in the file lines.txt
  });

This example executes the shell command cat lines.txt, then pipes the output to wc -l, and then collects the output through a callback that prints the number of lines in lines.txt

Here is another example:

var $p = require('procstreams');

$p('mkdir foo')
  .and('cp file.txt foo/')
  .and('rm file.txt')
    .on('exit', function() {
      console.log('done');
    });

This example executes mkdir foo, and if that succeeds, it executes cp file.txt foo/, and if that succeeds, it executes rm file.txt. In shells scripting you'd write this as:

mkdir foo && cp file.txt foo/ && rm file.txt

The .and(...) is the same as && in the shell scripting.

Procstreams also support .or(...), which is || in the shell and .then(...), which is ; in the shell.

Here is an example:

var $p = require('procstreams');

$p('mkdir foo')
  .then('cp file.txt file2.txt')
  .or('echo "failed" > ~/notify')

This example mkdirs foo, then copies file.txt to file2.txt, if that fails, it echos "failed" to ~/notify. Shell equivalent:

mkdir foo; cp file.txt file2.txt || echo "failed" > ~/notify

See procstreams documentation on GitHub for full info on other thingies it supports.

You can install procstreams through npm as always:

npm install procstreams

Procstreams on GitHub: https://github.com/polotek/procstreams.

Sponsor this blog series!

Doing a node.js company and want your ad to appear in the series? The ad will go out to 14,000 rss subscribers, 7,000 email subscribers, and it will get viewed by thousands of my blog visitors! Email me and we'll set it up!

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!

Awesome news everyone! We launched new design for Browserling! We also switched to Stripe for accepting payments and also added a bunch more browsers!

The new design is much cleaner, and everything is driven through ajax calls, we don't even use HTML templates anymore!

Here is a screenshot of Browserling with the new design:

Browserling is interactive cross-browser testing tool that allows you to see what your webpage looks like in Internet Explorer, Firefox, Chrome, Opera, and Safari.

This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->

node logoHello everyone! This is the 14th post in the node.js modules you should know about article series.

The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library, the sixth was about read - easy reading from stdin, the seventh was about ntwitter - twitter api for node, the eighth was about socket.io that makes websockets and realtime possible in all browsers, the ninth was about redis - the best redis client API library for node, the tenth was on express - an insanely small and fast web framework for node, the eleventh was semver - a node module that takes care of versioning, the twelfth was cradle - a high-level, caching, CouchDB client for node, the thirteenth was jsonstream - streaming JSON parsing library.

Today I'm gonna introduce you to everyauth by Brian Noguchi. Everyauth is a connect middleware that allows you to setup authentication for your app via facebook, twitter, google, vimeo, tumblr, 4square, etc.

Here is a list of all the sites you can use to login into your app:


Everyauth supports a plenty of sites.

Everyauth supports OpenID, Google, Twitter, LinkedIn, Yahoo, Readability, Dropbox, Justin.tv, Vimeo, Tumblr, Facebook, Github, Instagram, Foursquare, Gowalla, 37signals, AngelList, Dwolla, Box.net.

Using it is as simple as setting up a middleware for connect:

var everyauth = require('everyauth');
var connect = require('connect');

var app = connect(everyauth.middleware());

And setting up config.json that contains secret keys from the sites you are going to be using for authentication:

module.exports = {
    fb: {
        appId: '111565172259433'
      , appSecret: '85f7e0a0cc804886180b887c1f04a3c1'
    },
    twit: {
        consumerKey: 'JLCGyLzuOK1BjnKPKGyQ'
      , consumerSecret: 'GNqKfPqtzOcsCtFbGTMqinoATHvBcy1nzCTimeA9M0'
    },
    github: {
        appId: '11932f2b6d05d2a5fa18'
      , appSecret: '2603d1bc663b74d6732500c1e9ad05b0f4013593'
    },
    // ...
};

Then you setup routes for logging in for each particular site you want to support (in this example facebook) and you're done:

var conf = require('./config.json');

var usersByFbId = {};

everyauth
  .facebook
    .appId(conf.fb.appId)
    .appSecret(conf.fb.appSecret)
    .findOrCreateUser(function (session, accessToken, accessTokenExtra, fbUserMetadata) {
      return usersByFbId[fbUserMetadata.id] ||
        (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));
    })
    .redirectPath('/');

You can install everyauth through npm as always:

npm install everyauth

EveryAuth on GitHub: https://github.com/bnoguchi/everyauth.

Sponsor this blog series!

Doing a node.js company and want your ad to appear in the series? The ad will go out to 14,000 rss subscribers, 7,000 email subscribers, and it will get viewed by thousands of my blog visitors! Email me and we'll set it up!

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!

This is going to be a super quick tutorial on how to accept payments with Stripe payment processor and node.js. At Browserling we're moving to Stripe right this very moment so I thought I'd write this quick post. Stripe is the most incredible payment processor - it took me like 30 minutes to figure everything out. Everything is well documented and works like a charm!

First, you will need the node-stripe module. Install it through npm, as always:

npm install stripe

Next, you'll need to login into Stripe, and setup a plan:


Setting up a new Stripe plan.

Next, you'll need to find the test and live keys that are used in the payment code. They are located in Account Settings -> API Keys.


Stripe keys are located in Account Settings -> API keys.

Next, you'll need to include Stripe's JavaScript library in your HTML code:

<script type="text/javascript" src="https://js.stripe.com/v1/"></script>

Next, you'll need to setup an HTML form with card name, cvc, expiration date, amount (in cents!). You don't need to ask the name or address, that stuff is old school:

<div id="stripe-form">
  <form action="/plans/browserling_developer" method="POST" id="payment-form">
    <div class="form-row">
      <div class="cc-text">Card Number</div>
      <input type="text" size="30" autocomplete="off" class="card-number"/>
    </div>
    <div class="form-row">
      <div class="cc-text">CVC</div>
      <input type="text" size="4" autocomplete="off" class="card-cvc"/>
    </div>
    <div class="form-row">
      <div class="cc-text">Expiration (MM/YYYY)</div>
      <input type="text" size="2" class="card-expiry-month"/>
      <span> / </span>
      <input type="text" size="4" class="card-expiry-year"/>
    </div>
    <input type="hidden" name="amount" value="2000" id="cc-amount">
    <button type="submit" class="submit-button">Submit Payment</button>
  </form>
</div>
<div id="error" class="hidden"></div>
<div id="success" class="hidden">Thanks for signing up at Browserling!</div>

Next, you'll need to generate a token when the form gets submitted, and submit it to your node.js application, instead of submitting credit card number and other info:

var publicStripeApiKey = '...';
var publicStripeApiKeyTesting = '...';

Stripe.setPublishableKey(publicStripeApiKey);

function stripeResponseHandler (status, response) {
  if (response.error) {
    $('#error').text(response.error.message);
    $('#error').slideDown(300);
    $('#stripe-form .submit-button').removeAttr("disabled");
    return;
  }
  
  var form = $("#payment-form");
  form.append("<input type='hidden' name='stripeToken' value='" + response.id + "'/>");

  $.post(
    form.attr('action'),
    form.serialize(),
    function (status) {
      if (status != 'ok') {
        $('#error').text(status);
        $('#error').slideDown(300);
      }
      else {
        $('#error').hide();
        $('#success').slideDown(300);
      }
      $('.submit-button').removeAttr("disabled");
    }
  );
}

// http://stripe.com/docs/tutorials/forms
$("#payment-form").submit(function(event) {
  $('#error').hide();
  // disable the submit button to prevent repeated clicks
  $('.submit-button').attr("disabled", "disabled");

  var amount = $('#cc-amount').val(); // amount you want to charge in cents
  Stripe.createToken({
    number: $('.card-number').val(),
    cvc: $('.card-cvc').val(),
    exp_month: $('.card-expiry-month').val(),
    exp_year: $('.card-expiry-year').val()
  }, amount, stripeResponseHandler);

  // prevent the form from submitting with the default action
  return false;
});

Next, you need to setup a route handler in node.js web server for all your plan names. In this tutorial I'll handle just browserling_developer plan:

var express = require('express');

var stripeApiKey = "...";
var stripeApiKeyTesting = "..."
var stripe = require('stripe')(stripeApiKey);

app = express.createServer(express.bodyDecoder);

app.post("/plans/browserling_developer", function(req, res) {
  stripe.customers.create({
    card : req.body.stripeToken,
    email : "...", // customer's email (get it from db or session)
    plan : "browserling_developer"
  }, function (err, customer) {
    if (err) {
      var msg = customer.error.message || "unknown";
      res.send("Error while processing your payment: " + msg;
    }
    else {
      var id = customer.id;
      console.log('Success! Customer with Stripe ID ' + id + ' just signed up!');
      // save this customer to your database here!
      res.send('ok');
    }
  });
});

That's it! This simple node.js code handles POST requests to /plans/browserling_developer, and creates a new customer at Stripe. Notice that it uses req.body.stripeToken and doesn't even touch credit card info.

I have never worked with a payment processor which was easier to setup. It's a pure pleasure to use Stripe!