Categories
node.js

Node.js: the basics

Install node.js (no need to be verbose, see website for more details)

$ node -v // Verify installation

Install the NPM (node package manager, this will allow you to install and manage node packages):
$ curl http://npmjs.org/install.sh | sh

$ npm –version // Verify version and installation of package manager

Creating your application and installing packages:

$ mkdir my-project/

$ cd my-project/

$ npm init --yes

$ npm install colors

Now you will see inside your directory the node_modules folder, and inside of it, the package “color” you have recently installed.

To use the newly installed package:

$ vi index.js

And then, inside index.js, type:

require(‘colors’); // Will include the package 'colors', and now you can use it as in the line below

console.log(‘smashing node’.rainbow);

To manage / import modules into your own project, you will need a package.json file in the root directory of it, something like:

{

    “name”: “my-colors-project”,

    “version”: “0.0.1”, // Notice how first versions in node start at 0.0.1,

    “dependencies”: {

      “colors”: “0.5.0” // The modules you need to export to make your module

    }

}

Modules installed this way end up inside your ./node_modules/ file, but you can also have relative modules, not installed inside node_modules, you just have to specify the local path to them.

Once that is setup, run:

$ npm install // Will fetch dependencies for you

$ npm publish // To make your package available for others to install.

Installing binary utilities is a bit different. For example, to install the express framework:

$ npm install -g express

And then, to create a site using express:

$ mkdir my-site

$ cd mysite

$ express

To search for available packages:

$npm search realtime // Search for the realtime package

To get more information about the package you just discover:

$ npm view realtime

—————————————————————————————–

An alternative way to do this:

$sudo npm install -g express@2.5.4 (or whatever version you need)

$expression your_app_name  // Expression is the framework

$cd your_app_name && npm install // That will install dependencies specified in the package.json manager. You can modify that file if you need more dependencies

$node app // Start your app at port 3000

After this, everything happens inside app.js, that is the file that will serve your app

Leave a Reply

Your email address will not be published. Required fields are marked *