Book Image

Mastering Node.js

By : Sandro Pasquali
Book Image

Mastering Node.js

By: Sandro Pasquali

Overview of this book

Node.js is a modern development stack focused on providing an easy way to build scalable network software. Backed by a growing number of large companies and a rapidly increasing developer base, Node is revolutionizing the way that software is being built today. Powered by Google's V8 engine and built out of C++ modules, this is a JavaScript environment for the enterprise.Mastering Node.js will take the reader deep into this exciting development environment. Beginning with a comprehensive breakdown of its innovative non-blocking evented design, Node's structure is explained in detail, laying out how its blazingly fast I/O performance simplifies the creation of fast servers, scalable architectures, and responsive web applications.Mastering Node.js takes you through a concise yet thorough tour of Node's innovative evented non-blocking design, showing you how to build professional applications with the help of detailed examples.Learn how to integrate your applications with Facebook and Twitter, Amazon and Google, creating social apps and programs reaching thousands of collaborators on the cloud. See how the Express and Path frameworks make the creation of professional web applications painless. Set up one, two, or an entire server cluster with just a few lines of code, ready to scale as soon as you're ready to launch. Move data seamlessly between databases and file systems, between clients, and across network protocols, using a beautifully designed, consistent, and predictable set of tools.Mastering Node.js contains all of the examples and explanations you'll need to build applications in a short amount of time and at a low cost, running on a scale and speed that would have been nearly impossible just a few years ago.
Table of Contents (20 chapters)
Mastering Node.js
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a calculator


Of course one would never bother to write an add-on to simply echo back strings. It is more likely that you will want to expose an API or interface to your Node programs. Let's create a simple calculator, with two methods: add and subtract. In this example, we will demonstrate how to pass arguments from JavaScript to methods within an add-on, and to send any results back.

The complete code for this example will be found in your code bundle. The meat of the program can be seen in this snippet, where we define an interface for our two methods, each one expect to receive two numbers as arguments:

#include <node.h>
#include <v8.h>

using namespace v8;

Handle<Value> Add(const Arguments& args) {
  HandleScope scope;

  if(args.Length() < 2) {
    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
    return scope.Close(Undefined());
  }

  if(!args[0]->IsNumber() || !args[1]->IsNumber()) {
    ThrowException(Exception::TypeError(String::New("Wrong arguments")));
    return scope.Close(Undefined());
  }

  Local<Number> num = Number::New(args[0]->NumberValue() + args[1]->NumberValue());
  return scope.Close(num);
}

Handle<Value> Subtract(const Arguments& args) {
  // Similar method to do subtraction...
}

void Init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("add"),
    FunctionTemplate::New(Add)->GetFunction());
  exports->Set(String::NewSymbol("subtract"),
    FunctionTemplate::New(Subtract)->GetFunction());
}

NODE_MODULE(calculator, Init)

We can quickly see that two methods have been scoped: Add and Subtract (Subtract is defined nearly identically with Add, with only a change of operator). Within the Add method we see an Arguments object (reminiscent of JavaScript's arguments object) that is checked for length (we expect two arguments) and type (we want numbers). Take a good look at how this method closes out:

Local<Number> num = Number::New(args[0]->NumberValue() + args[1]->NumberValue());
return scope.Close(num);

While there seems to be a lot going on, it is really rather simple: V8 is instructed to allocate space for a Number variable with name num, to be assigned the value of adding our two numbers together. When this operation has been completed, we close out the execution scope and return num. We don't have to worry about memory management for this reference, as that is automatically handled by V8.

Finally, we see in the following chunk not only how this particular program defines its interface, but how, at a deep level, Node modules and the exports object are in fact associated:

void Init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("add"),
    FunctionTemplate::New(Add)->GetFunction());
  exports->Set(String::NewSymbol("subtract"),
    FunctionTemplate::New(Subtract)->GetFunction());
}

As in our "hello" example, here we see the new symbols (these are just types of strings) add and subtract, which represent the method names for our new Node module. Their function is implemented with the easy-to-follow FunctionTemplate::New(Add)->GetFunction()).

Using our calculator from a Node program is now rather easy:

var calculator = require('./build/Release/calculator');

console.log(calculator.add(2,3));
console.log(calculator.subtract(3,2));

When this is executed you will see the following displayed in your terminal:

5
1