Node.js - tutorial - basics

revision:


What is node.js?

Node.js is an open source server environment, that runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) and that uses JavaScript on the server.

When receiving a file request, node.js sends the task to the computer's file system and is ready to handle the next request.
When the file system has opened and read the file, the server returns the content to the client.
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.

What can node.js do? Node.js can generate dynamic page content. It can create, open, read, write, delete, and close files on the server. It collects form data and can add, delete, modify data in your database.

What is a node.js file? Node.js files contain tasks that will be executed on certain events. A typical event is someone trying to access a port on the server. Node.js files must be initiated on the server before having any effect. Node.js files have extension ".js".


Node.js console

Node.js comes with virtual environment called REPL (aka Node shell).

REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code.
To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type "node". It will change the prompt to > in Windows and MAC.

You can now test pretty much any Node.js/JavaScript expression in REPL.

To exit from the REPL terminal, press Ctrl + C twice or write ".exit" and press Enter.

The following table lists important REPL commands:

REPL Command - Description
.help - display help on all the commands
tab Keys - display the list of all commands.
Up/Down Keys - see previous commands applied in REPL.
.save filename - save current Node REPL session to a file.
.load filename - load the specified file in the current Node REPL session.
ctrl + c - terminate the current command.
ctrl + c (twice) - exit from the REPL.
ctrl + d - exit from the REPL.
.break - exit from multiline expression.
.clear - exit from multiline expression.


Node.js fundamentals

Node.js includes following primitive types: string, number, boolean, undefined, null, and RegExp. Everything else is an object in Node.js.

JavaScript in Node.js supports loose typing like the browser's JavaScript. Use "var keyword" to declare a variable of any type.

Object literal syntax is same as browser's JavaScript.

Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript.

A function can have attributes and properties also.
It can be treated like a class in JavaScript.

Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.

Each Node.js script runs in a process. It includes process object to get all the information about the current process of Node.js application.

Node's JavaScript is different from browser's JavaScript when it comes to global scope.

In the browser's JavaScript, variables declared without var keyword become global. In Node.js, everything becomes local by default.
- In a browser, global scope is the window object. In Node.js, global object represents the global scope.
- To add something in global scope, you need to export it using "export" or "module.export".
The same way, import modules/object using "require() function" to access it from the global scope.


Node.js modules

Consider modules to be the same as JavaScript libraries: a set of functions you want to include in your application.

Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope.
Also, each module can be placed in a separate .js file under a separate folder.

Node.js includes three types of modules: core modules, local modules, third party modules.

The core modules - or built-in modules - include bare minimum functionalities of Node.js.

These core modules are compiled into its binary distribution and load automatically when Node.js process starts.
However, you need to import the core module first in order to use it in your application.
These built-in modules can be used without any further installation.
To include a module, use the require() function with the name of the module.

Example:

var http = require('http');.

The following table lists some of the important core modules in Node.js.

Core module - description
http - http module includes classes, methods and events to create Node.js http server.
url - url module includes methods for URL resolution and parsing.
querystring - querystring module includes methods to deal with query string.
path - path module includes methods to deal with file paths.
fs - fs module includes classes, methods, and events to work with file I/O.
util - util module includes utility functions useful for programmers.

You can create your own modules and easily include them in your applications.

These "local modules" are created locally in your Node.js application.
They include different functionalities of your application in separate files and folders.
You can also package them and distribute them via NPM, so that the Node.js community can use them.

The following example creates a module that returns a date and time object:

Example:

      exports.myDateTime = function () {
        return Date();
      };
      

Use the "exports" keyword to make properties and methods available outside the module file. Save the code in a file with .js extension.
The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.

Include your own modules: to use local modules in your application, you need to load them using require() function in the same way as a core module.

However, you need to specify the path of the JavaScript file of the module. Notice that "./" is used to locate the module, which means that the module is located in the same folder as the Node.js file.


Node.js built-in modules

Module - Description
assert - provides a set of assertion tests
buffer - to handle binary data
child_process - to run a child process
cluster - to split a single Node process into multiple processes
crypto - to handle OpenSSL cryptographic functions
dgram - provides implementation of UDP datagram sockets
dns - to do DNS lookups and name resolution functions
domain - deprecated. To handle unhandled errors
events - to handle events
fs - to handle the file system
http - to make Node.js act as an HTTP server
https - to make Node.js act as an HTTPS server.
net - to create servers and clients
os - provides information about the operation system
path - to handle file paths
punycode - deprecated. A character encoding scheme
querystring - to handle URL query strings
readline - to handle readable streams one line at the time
stream - to handle streaming data
string_decoder - to decode buffer objects into strings
timers - to execute a function after a given number of milliseconds
tls - to implement TLS and SSL protocols
tty - provides classes used by a text terminal
url - to parse URL strings
util - to access utility functions
v8 - to access information about V8 (the JavaScript engine)
vm - to compile JavaScript code in a virtual machine
zlib - to compress or decompress files


Node.js HTTP module

The built-in HTTP module allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method.

Example: var http = require('http');

Node.js as a web server: the HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Use the createServer() method to create an HTTP server. (see: demo_http.js)

Add an HTTP header: if the response from the HTTP server is supposed to be displayed as HTML, you should include an HTTP header with the correct content type.

Example:

        var http = require('http');
        http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write('Hello World!');
          res.end();
        }).listen(8080);
      

The first argument of the res.writeHead() method is the status code; 200 means that all is OK.
The second argument is an object containing the response headers.

Read the query string. The function passed into the http.createServer() has a "req" argument that represents the request from the client, as an object (http.IncomingMessage object).

This object has a property called "url" which holds the part of the url that comes after the domain name.

Split the query string. There are built-in modules to easily split the query string into readable parts, such as the URL module.


Node.js file system module.

The Node.js file system module allows you to work with the file system on your computer. To include the file system module, use the require() method

Example: var fs = require('fs');.

Read files: the fs.readFile() method is used to read files on your computer.

Example:

      var http = require('http');
      var fs = require('fs');
      http.createServer(function (req, res) {
          fs.readFile('demofile1.html', function(err, data) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          res.write(data);
          return res.end();
        });
      }).listen(8080);
      

Create files: the file system module has methods for creating new files: fs.appendFile(), fs.open(), fs.writeFile.()

The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created.

The fs.open() method takes a "flag" as the second argument. If the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created.

The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created.

Update files: the file system module has methods for updating files: fs.appendFile(), fs.writeFile()

The fs.appendFile() method appends the specified content at the end of the specified file.

The fs.writeFile() method replaces the specified file and content.

Delete files: to delete a file with the file system module, use the fs.unlink() method, which deletes the specified file.

Rename files: to rename a file with the file system module, use the fs.rename() method, which renames the specified file.

Upload files: you can also use Node.js to upload files to your computer.


Node.js URL module

The built-in URL module splits up a web address into readable parts. To include the URL module, use the require() method.

Example: var url = require('url');.

Parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties.

Node.js file server: we know how to parse the query string and how to make Node.js behave as a file server. Let us combine the two, and serve the file requested by the client.


Node.js events

Events in node.js: every action on a computer is an event, like when a connection is made or a file is opened.

Objects in node.js can fire events, like the readStream object fires events when opening and closing a file.

Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own events.

To include the built-in events module use the require() method.
In addition, all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object.

Example:

      var events = require('events');
      var eventEmitter = new events.EventEmitter();
      

You can assign event handlers to your own events with the EventEmitter object. To fire an event, use the emit() method.

Example:

        var events = require('events');
        var eventEmitter = new events.EventEmitter();

        //Create an event handler:
        var myEventHandler = function () {
          console.log('I hear a scream!');
        }

        //Assign the event handler to an event:
        eventEmitter.on('scream', myEventHandler);

        //Fire the 'scream' event:
        eventEmitter.emit('scream');