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/joe/";
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

Node.js Module system

Node.js Module

back to JavaScript in Depth

Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

JavaScript in Depth

Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics

Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment

String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Check Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”

Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

Misc

  1. Set Object
  2. Map Object
  3. Try Catch Throw Finally
  4. Import/Export
  5. Promise
  6. Proxy
  7. ES2015 Features
  8. How to Convert ES5 to ES2015
  9. Style Guide
  10. Semicolon Rules
  11. Exclamation Before Function
  12. How to Determine Strict Mode?
  13. x.y.z Associativity
  14. Function Chain
  15. Random Number, Range, Integer, Element
  16. Timing JS Code
  17. Range Function for Array
  18. Random Array Element, Randomize Array
  19. Tagged Template String
  20. String to Number
  21. Format Number

Object Reference

  1. the Global Object
  2. Object 🙼 Object.prototype
  3. Array 🙼 Array.prototype
  4. Function 🙼 Function.prototype
  5. String 🙼 String.prototype
  6. RegExp 🙼 RegExp.prototype 🙼 RegExp Syntax
  7. Date 🙼 Date.prototype
  8. Set ⭐🙼 Set.prototype
  9. Map ⭐🙼 Map.prototype
  10. JSON
  11. Math
  12. Reflect
  13. Symbol ⭐🙼 Symbol.prototype
  14. Number 🙼 Number.prototype
  15. Boolean 🙼 Boolean.prototype

DOM How-To

  1. Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree

DOM Overview

  1. Browser Window Object, Document Object Model
  2. Intro to Event-Based Programing
  3. JavaScript Load Order
  4. What is Live Object
  5. NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes

Basic DOM Methods

  1. Basic DOM Methods
  2. Node Type, Name, Value
  3. Navigate DOM Tree

HTML Form

  1. HTML Form
  2. Visit URL in a New Window
  3. Instant Field Validation
  4. Input Field Validation
  5. HTML: Input Range Slider

DOM How To

  1. Encode URL, Escape String
  2. Browser Info, Navigator Object
  3. Get URL (window.location)
  4. Web Cookies
  5. Web Storage
  6. Find Window Width
  7. Find Element Width
  8. WebSocket

Web Scripting Examples

  1. Disable Right Click
  2. document.write
  3. Image Rollover
  4. Pop-up New Window
  5. Digital Clock
  6. Stopwatch
  7. Fade a Element
  8. Fade a Element Using CSS Transition
  9. Shake Element
  10. How to Create Tooltip
  11. Falling Snow Effect
  12. JavaScript: Floating Box Following Scroll

DOM Misc

  1. Value of “this” in Event Handler
  2. Event Delegation
  3. Get Current Script Tag
  4. insertAfter Element
  5. Randomize List
  6. create Document Fragment
  7. innerHTML, nodeValue, textContent, innerText?

jQuery

  1. jQuery Basics
  2. jQuery() vs querySelectorAll()
  3. Write JQuery Plugin

node.js