JavaScript-based environment to create web-servers, networked applications or to perform helpful tasks e.g. minifying or concatenating
A free open source framework
Introduction > What is Node.js
Can have lots of connections sending information simultaneously
Asynchronous I/O and non-blocking
It's fast, lightweight, efficient, and has ability to use JavaScript on both frontend and backend
Good for real-time applications
Serves as a proxy server
Introduction > Why Node.js
Introduction > So what's this NPM?
Node.js uses a different set of API's that are suitable for backend development
web JavaScript is limited with backend support due security reasons
Introduction > Difference Node.js & web JS
Download the latest version from the website
Run the installer
Follow the prompts in the installer
Restart your computer
Installation > How to install
Open Command Line tool
Use to check if Node.js is installed and what version
Use to check if NPM is installed and what version
Installation > Test the installation
node -v
npm -v
Create a file called test.js
Add to the file
Go to the Command Line and type
Installation > Create test file and run it
console.log('Some random text here');
node test.js
Console > Methods
let welcomeMessage = 'Hello World';
let errorMessage = 'Fail!';
let developer = {
favouriteLanguage: "JavaScript",
age: 23
}
// Prints out 'Hello' to the console
console.log(welcomeMessage);
// Prints error message to the console
console.error(errorMessage);
// Prints out an object
console.dir(developer);
Read Eval Print Loop > What is REPL?
Represents a computer environment where a command is entered and the system responds with an output in an interactive mode
Can be started by typing in in the console
node
Read Eval Print Loop > REPL Commands
// Terminate the current command
ctrl + c
// Terminate the Node REPL
ctrl + c (twice) or ctrl + d
// Going through command history and modify commands
Up/Down keys
// List of current commands
tab
// List of all commands
.help
// Exit from multiline expression
.break or .clear
// Save the current REPL session to a file
.save filename
// Load file content in current REPL session
.load filename
Buffer > What is a Buffer?
Used to store binary data while reading data from a file or when receiving packages over the network
Options with Buffers:
Buffer > Examples
// Creating a Buffer
let foo = new Buffer(10); // 10 = number of octets
let foo = new Buffer([25, 30, 35, 40, 45]);
// Reading a Buffer
buf.toString([encoding][, start][, end])
// start and end are index numbers
// Writing to Buffers
buf.write(string[, offset][, length][, encoding])
// length is number of bytes to write
// Concatenating
Buffer.concat(list[, totalLength])
// Convert to JSON
buf.toJSON()
// Compare Buffers
buf.compare(otherBuffer);
Global objects > What are they?
Objects that are already included in all available modules
Can be:
Global objects > Examples
// Print information
console
// Get information about the current process
process
// Run callback cb after x milliseconds
setTimeout(cb, ms)
// Stops the timer that was set with setTimeout
clearTimeout(t)
// Runs callback repeatedly for x milliseconds
setInterval(cb, ms)
// The filename of code that is being executed
console.log(__filename);
// The directory of the script that's executing
console.log(__dirname);
Streams > What are Streams?
Objects that let you read data from a source or write data to a destination
4 type of streams:
Each type is an EventEmitter instance and throws several events, such as data, end, error and finish
Process > What is it?
Every script runs in a process
Every process includes a process object to get all information and control about the current process
Process > Events
// Emitted when the event loop is empty and there is nothing in schedule
beforeExit
// Emitted when the process is about to exit
exit
// Emitted when an exception goes back to the event loop
uncaughtException
Callbacks > What is a Callback?
An asynchronous equivalent for a function
It's called at the completion of a task
Callbacks > Blocking call
The script blocks until it reads the file and then only it proceeds to end the program
const FS = require("fs");
let data = FS.readFileSync('test.txt');
console.log(data.toString());
console.log('The end');
// Output: The data from test.text followed by "The end"
Callbacks > Non-blocking call
The script doesn't wait, it proceeds to print to the console while the script still continues reading the file.
const FS = require("fs");
FS.readFile('test.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log('The end');
// Output: "The end" followed after by the data from test.txt
Modules > What is a Module?
A set of functions
You can create your own Module and include
it in your application
Types of Modules:
Modules > Core Modules
// Creating a HTTP server (includes classes, methods and events)
http
// URL resolution and parsing (includes methods)
url
// Dealing with query strings (includes methods)
querystring
// Dealing with file paths (includes methods)
path
// Working with file I/O (includes classes, methods and events)
fs
// Utility functions
util
Modules > Core Modules > Include a Core Module
const FOO = require('core_module');
Modules > Local Modules
Locally created modules in your application
Can include different functionalities separated in files and folders
Modules > Local Modules > Loading a Local Module
const FOO = require('local_module');
A main loop that listens for events
Triggers a callback function when an event is detected
There are multiple in-built events which are used to bind events and event listeners
Event Loops > What are Event Loops?
All objects which emit events are the instances of events.EventEmitter
EventEmitter class is within the events module
Event Loops > EventEmitter
// Use require (or import) to import the module
const EVENTS = require('events');
// Creating an eventEmitter object
let eventEmitter = new EVENTS.EventEmitter();
Event Loops > EventEmitter > Events
// Event emitted when a listener is added
newListener
// Event emitted when a listener is removed
removeListener
Event Loops > EventEmitter > Methods
// Returns an array of listeners
listeners(event)
// Adding a listener at the and of the listeners array
addListener(event, listener)
// Adding a listener at the end of the listeners array
on(event, listener)
// Removes all listeners
removeAllListeners([event])
// Removing a listener from the listener array
removeListener(event, listener)
// Adding a one time listener to the event
once(event, listener)
// EventEmitters will give a warning if more than x
// (usually 10) listeners are added to an event
setMaxListeners(n)
File system > What is it?
Using simple wrappers around POSIX functions using File I/O
Can be imported using the require method
fs module has synchronous and asynchronous forms
Asynchronous is recommended since it's non-blocking
File system > File methods
// Opening a file
fs.open(path, flags[, mode], callback)
// Getting information from a file
fs.stat(path, callback)
// Closing a file
fs.close(fd, callback)
// fd = file descriptor returned by fs.open()
// Reading a file
fs.read(fd, buffer, offset, length, position, callback)
// fd = file descriptor returned by fs.open()
// Writing to a file
fs.writeFile(filename, data[, options], callback)
// Deleting or truncating a file
fs.unlink(path, callback) // Deleting
fs.ftruncate(fd, len, callback) // Truncate
File system > Directory methods
// Create a directory
fs.mkdir(path[, mode], callback)
// Mode = permission
// Read a directory
fs.readdir(path, callback)
// Delete/remove a directory
fs.rmdir(path, callback)
Debugging > Core debugger
const FS = require('fs');
FS.readFile('test.txt', 'utf8', function (err, data) {
// Built-in non-graphic debugging tool
debugger;
if(err) throw err;
console.log(data);
});
Run the following command:
node debug app.js
Debugging > Core debugger > Commands
// Add the variable or expression into watch
watch
// See the values of what you have added into watch
watcher
// Pause the running code
Pause
// Stop at the next statement
next
// Step in function
step
// Step out of function
out
// Continue to execute and stop at the debugger statement
cont
Example > Read data
// file.txt
Michael A 2
Jeroen B 2
Nando C 1
Nick B 8
Ruben D 5
// Load the fs (filesystem) module
const FS = require('fs');
// Reads the contents of the file
FS.readFile('file_log.txt', function (err, logData) {
// Displays an exception and end app if an error occurred
if (err) throw err;
// logData is a Buffer, then converts to a string
let text = logData.toString();
});
Example > Add parsing data
// Load the fs (filesystem) module
const FS = require('fs');
// Reads the contents of the file
FS.readFile('file_log.txt', function (err, logData) {
// Displays an exception and end app if an error occurred
if (err) throw err;
// logData is a Buffer, then converts to a string
let text = logData.toString();
let results = {};
// Break up the file into lines.
let lines = text.split('\n');
// Go through every line
lines.forEach(function(line) {
// Divides the string with a space
let parts = line.split(' ');
// Selects the second item of the Array
let name = parts[0];
// Selects the third item of the Array
let count = parseInt(parts[2]);
if(!results[name]) {
results[name] = 0;
}
results[name] += parseInt(count);
});
console.log(results);
});
Resources > Useful links