Node.js Tutorial

By Xah Lee. Date: . Last updated: .

This page is a tutorial of node.js.

You should already know the basics of JavaScript. If not, see

JavaScript Basics

Install

Go to http://nodejs.org/ site, and download the binary. There's a binary for Linux too, no need to compile.

Run node

run node in terminal 2017 09 15 63613
node.js command line

Once installed, go to terminal, type node to start the command line.

To run a js script, type:

node filename

globals

There are these global objects:

For full list, see: ⬢ Global Objects

// print fullpath of current script
console.log(__filename);

// print dir path of current script
console.log(__dirname);
global.bb = 4;
console.log(global.bb); // 4

Use console.dir(…) to inspect objects, including builtin Node objects. This is handy to see what property/methods a object has. ⬢ console.dir(obj)

console.dir(global); // huge output. try it.

console.dir(…) is actually a wrapper to util.inspect() method. The “inspect” takes some useful arguments.

// print all properties of the require('net') module, using inspect method from module util
console.log(
 require('util').inspect( require('net'), { showHidden: true, depth: null })
);

⬢ util.inspect(object, [options])

show node.js version from runtime

show node.js version from runtime

// show node.js version from runtime
console.log(process.version);
// v6.0.0

command line args

Use process.argv to get arguments from command line.

// sum numbers from command line args
// save this file as x.js
// run it in terminal, type
// node x.js 3 4
// prints 7

const tt = process.argv;
tt.splice(0,2);

console.log(
tt.reduce(
    ((x,y) => (parseInt(x) + parseInt(y)))
)
);

⬢ process

count lines (sync version)

// open file, count number of newlines

// save this file as x.js
// run it in terminal, type
// node x.js filepath
// prints number of newline chars

const fs = require('fs');

const fpath = process.argv[2];

const buf = fs.readFileSync(fpath);
const ss = buf.toString("utf8");

console.log(
 ss.match(/\n/g).length
);

⬢ Buffer

count lines (async version)

// open file, count number of newlines. async.

// save this file as x.js
// run it in terminal, type
// node x.js filepath
// prints number of newline chars

const fs = require('fs');

const fpath = process.argv[2];

fs.readFile(fpath, function (err, data) {
    if (err) {throw err;} else {
        count = data.toString("utf8").match(/\n/g).length;
        console.log(count);
    }
});

⬢ fs.readFile(filename, [options], callback)

⬢ Buffer

list files

// given a dir path and extension such as "txt", print file names with that extension

const ff = require('fs');
const pp = require('path');

const inputDir = "/home/jane/";
const fExt = "txt";

const printFileName = ((err, fileList) => {
               if (err) {throw err;} else {
                   fileList.filter(
                       ((x) => (pp.extname(x) === "." + fExt))
                   ) .forEach( ((x) => (console.log(x))) )
               }
           });

ff.readdir(inputDir, printFileName );

⬢ fs.readdir(path, callback)

modules

Each module corresponds to a file.

Each module and its file have the same name.

⬢ Modules

Net Module for writing TCP Server

net.createServer() return a server object.

net.connect(…) and net.createConnection(…) are aliases.

net.createConnection(…) return a socket object.

⬢ net

Node Package Manager: npm

Node's package manager is npm. (home https://npmjs.org/) npm is bundled with Node (v0.10.x).

Type npm help to get started using npm.

$ npm help

Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, edit, explore, get,
    help, help-search, i, init, install, install-test, it, link,
    list, ln, logout, ls, outdated, owner, pack, ping, prefix,
    prune, publish, rb, rebuild, repo, restart, root,
    run-script, s, se, search, set, shrinkwrap, star, stars,
    start, stop, t, tag, team, test, tst, un, uninstall,
    unpublish, unstar, up, update, v, version, view, whoami

npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /home/xah/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@3.8.6 /home/xah/apps/node-v6.0.0-linux-x64/lib/node_modules/npm

See also: Node.js Video Tutorial by Ryan Dahl, with Annotation

back to JavaScript in Depth

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth