הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Node.JS Basics

Getting Started

Install Node.js by downloading it from: http://nodejs.org/download/. A good place to start reading about Node is Node Beginner's Book.

Other useful resources include:

  1. Node API Docs
  2. Learning Node.JS Tutorial
  3. Introduction To Node.JS Screencast (With Ryan Dahl)

Since Node.JS is just a javascript engine, you can write any JS code you want and run it from the console using Node.JS. Here's a small Hello World Node code:

var x = 5;
var y = 9;
 
var z = x + y;
 
console.log('5 + 9 = ' + z);

If the code is saved in a file named app.js, you can run it from the console using node app.js

You will note since Node doesn't run in a browser, it's missing the browser JS objects such as window and document.

The Module Pattern

Browser based JavaScript uses window as a global object. You can put anything on window, and it'll be available throughout your program (and, as a bonus, if you forget to specify a namespace window is the default).

The use of a global window object has put many JavaScript developers in a problem. Every time we want to write a library and distribute it, we are forced to add names to the global object, so our users will be able to use it. For example, jQuery adds the $ function, underscore adds the _ function, and other libraries add their own code.

A better solution is implemented in Node. Each file has its own global object (called exports). When a developer loads an external file, she chooses a local name for the loaded module's global object. This way, no global object is needed to sync between files.

Using A Module With Require

// require loads a module
var http = require('http');

// you can now use http as the name for the exports object defined inside the http module

Create A New Module

// this function is not exported
var private_function = function(x) {
  return x * 2;
};

// both PI and add are exported
exports.PI = 3.14;

exports.add = function(x, y) {
  return x + y;
};

Using The Custom Module

var math = require('./mymod');

// now math refers to the module's global object (exports)
console.log( math.PI );

Note the use of ./modname in the require.
If a module name starts in a letter, node looks for the module in the following order:

  1. ./node_modules/module_name.js
  2. ./node_modules/module_name/index.js
  3. ./node_modules/module_name/package.json
  4. $NODE_PATH/module_name.js
  5. $NODE_PATH/module_name/index.js
  6. $NODE_PATH/module_name/package.json

A module name can also be an absolute or relative path, and then Node will look for the module in the absolute path or in a path relative to the location of the file.

Require a module starting with ./... to use a module from current file's path.
Require a module by name to use a module from default search pat

Node Package Management

For the module pattern to work, there are several issues need to be addressed:

  • Module Versioning
  • Module Dependencies
  • Module Distribution

Node uses a package file to identify the version and dependencies of a module, as well as other metadata on the package. The package file is JSON formatted.
Some packages are written for distribution, and thus include metadata which describes their repository URL, search keywords and license, while other packages are only written for internal use and skip these fields.

Here's a simple package.json file for a package:

{
    "name" : "my-app",
    "version" : "0.0.1",
    "private" : true,
    "dependencies" : {
        "colors" : "*"
    }
}

Note the private: true field which states this package is not meant to be distributed.
For a more comprehensive review of the options you can write in a package.json file, refer to: http://package.json.nodejitsu.com/

Using The Package Manager

Since every node package out in the open has a package.json file, an automated tool called npm is there to help you find and install new packages.

The easiest way to use npm is to have a package.json for you own project which specified dependencies. Then, in the project's directory run: npm install. This will tell npm to automatically find and download your needed packages, and install them in the local ./node_modules path.

The online repository for node packages is available as a web site at: https://npmjs.org/.