Node.js Basic

Day 1

What's Node?

Node.js

- Is a javascript runtime built on top of V8 engine.

- Free and open source, also available on almost every OS and CPU architecture

- Node.js uses asynchronous, event-driven, non-blocking I/O

- Is single-threaded to developer perspective

- Node.js was first built at 2009 by Ryan Dahl and was released for the first time in 2011.

- Now maintained and developed by community & enterprises under Node.js Foundation.

So, it's a javascript runtime?

Why Node.js

Why Node.js

1. It's fast

2. It has huge and the fastest growing community!

3. Enterprises are using it in production!

4. We at DyCode also use Node.js a lot!

5. Stability

It's fast

Node.js uses asynchronous I/O which means that node process doesn't wait I/O operation, instead node.js uses callback to signal I/O op completition.

Huge and fast-growing community

There was more than 100K modules published to npm by the end of 2014.

 

And 300K published modules by the end of September 2016. (Announced at Node Interactive Europe)

Huge and fast-growing community (cont'd)

More than 5 millions (yes, 5 with 6 zeros) users!

(Announced at Node Interactive Europe, September 2016)

 

The number of downloads for every version (v4, v6, and v7) keep increasing over time!

Used by enterprises in production

- Netflix

- LinkedIn

- GoDaddy

- Paypal

- And many more

DyCode uses Node.js a lot!

We use Node.js to build RESTful JSON API for mobile apps.

DycodeX -- DyCode's subsidiary -- uses Node.js to build back-end for handling real-time intensive data.

DycodeX also uses Node.js on low-power IoT devices!

Stability

They release a semver major update every six months. Everytime an odd version released, the previous version will transition to a LTS active version for 18 months.

 

 LTS version will have additional year of maintenance before it reach the end of it's life.

 

Current LTS Version: v4 and v6 (latest)

When to use Node.js?

And when not to?

Let's start!

By learning Javascript language first

Javascript

Javascript is a programming language developed in 1995 with name LiveScript by Brendan Eich.

Javascript is the main language for developing dynamic web pages or web application.

Javascript is standarized under ECMA-262 Specification.

ES2015 / ES6 is almost implemented by all new version of browsers. With ES7 being actively developed and shipped to newest browsers as experimental features.

JS: Basic Syntax

console.log('Hello world!');

# Did you know that semicolons are optional?

console.log('Hello')

var string = 'World'

console.log(string)

# You need semicolons if you're running multiple statement in one line

const message = 'Hello world'; console.log(message);

Always adding semicolon at the end of every statement is considered a good practice!

JS: Basic Syntax

console.log('Hello world!');

# Did you know that semicolons are optional?

console.log('Hello')

var string = 'World'

console.log(string)

# You need semicolons if you're running multiple statement in one line

const message = 'Hello world'; console.log(message);
// You know, both C and C++ style of comments are supported

/* This also works */

let count = 0;
count += 1;

// JS doesn't really care about whitespaces.

// And, JS is a case-sensitive language.

const variable = 'A constant variable';

// and

const Variable = 'Another constant';

// are different things

Variables

console.log('Hello world!');

# Did you know that semicolons are optional?

console.log('Hello')

var string = 'World'

console.log(string)

# You need semicolons if you're running multiple statement in one line

const message = 'Hello world'; console.log(message);
// Before ES6 / ES2015, your only way to declare variable:

var variableName = 1;
var aNumber = 2;

// After ES6

var count = 0;
let sum = 1;
const pi = 3.14;

pi = 3.1415;

// ERROR! You can not re-assign value to a const!

Variable Naming Rules

// Naming rules

var i = 0; // valid
const WhoAmI = 'Alwin'; // valid
const $me = 'Alwin'; // valid
const _alsoMe = 'Alwin'; // valid

let 123satuduatiga = 123; // INVALID! Name should not start with numbers
const default = 1; // INVALID! "default" is a reserved keyword!
let break = true; // INVALID! "break" is also a reserved keyword!

Variable Types

// Number
const pi = 3.14;
const state = 19;
const notANumber = NaN;
const infinity = Infinity;
const negativeInfinity = -Infinity;

// String
const message = 'Hello javascript';
const anotherMessage = "Double quotes are allowed too!";

// Boolean
const isItTrue = true;
const isItFalse = false;

// Array
const sequence = [1, 2, 3];
const mixed = [1, 'JS', 3, true, null];

// Function
const add = (a, b) => a + b;
const multiply = function (a, b) {
    return a * b;
};

Variable Types

// Object
const cat = {
    sound: 'Meow',
    talk() {
        console.log(this.sound),
    },
};
const none = null; // what the... ?
const date = new Date();
const array = []; // wait, what?

// symbol, new in ES6

const sym = Symbol();


// Undefined
let something;
const undef = undefined;

Variable Scopes

// these are global variable
const a = 1;
const b = 2;

(function() {
    // except this one
    const a = 20;
    console.log(a) // output 20
}())
console.log(a) // output 1

// block scope, only for let and const
if (a === 1) {
    const b = 3;
    console.log(b); // output 3
}
console.log(b); // output 2

// var is not block-scoped

if (b === 2) {
    var c = 4;
    console.log(c); // output 4
}

console.log(c); // output 4

Operators

// Arithmetic
1 + 2 // 3
2 * 3 // 6
4 / 2 // 2
4 % 2 // 0

// Logical

1 || 1 // true
1 || 0 // true

1 && 1 // true
1 && 0 // false

// Negation
!1 // false
!true // false

Operators

// Comparison

a == b // check whether a is equal with b
a === b // check whether a is equivalent with b

1 == 1 // true
1 === '1' // false

a != b // check whether a is not equal with b
a !== b // check whether a is not equivalent with b

1 != '1' // false
1 !== '1'  // true


a > b
a >= b
a < b
a <= b

Operators, one more thing

// + becomes a concatenation operator if at least one of the operands is string

1 + 'dua' === '1dua';
'dua' + 'tiga' === 'duatiga';
NaN + 'as' === 'NaNas';
null + 'lis' === 'nullis';
[1, 2, 3] + 'a' === '1,2,3a';


// Except if the other operand is an object literal

{} + 'a' // output is NaN

// but
NaN != NaN 
NaN !== NaN

isNaN({} + 'a') === true

Conditional - If-else

const a = 10;
if (a === 10) {
    console.log('Ten!');
} else {
    console.log('Definitely not ten :(');
}


const b = 15;
if (b < 10) {
    console.log('b < 10');
} else if (b <= 20) {
    console.log('b < 20');
} else {
    console.log('b > 20');
}

Conditional - switch case

const status = 'failed';
switch (status) {
    case 'succeed':
        console.log('Success!');
        break;
    case 'failed':
        console.log('Failed :(');
        break;
    default:
        console.log('Unknown: ' + status);
}

// output: Failed :(

const numeric = 20;
switch (numeric) {
    case 10:
        console.log('Definitely 10!');
    case 20:
        console.log('Definitely 20!');
    default:
        console.log('Maybe other than 20 and 10?');
}

/* output:
 * Definitely 20!
 * Maybe other than 20 and 10?
 */

Conditional - ternary

const a = 10;
const b = (a === 10) ? 20 : 30;

console.log(b);

// output: 20

Looping

// for loop

for (let i = 0; i < 10; i++) {
 // do something...
}

// while loop

let a = 0;
while (a < 10) {
    // do something
    a++;
}

// do-while loop

let b = 1; 

do {
    console.log(b);
    b += 2;
} while (b < 10);

Loop control

// break after i === 5

for (let i = 0; i < 10; i++) {
    if (i > 5) {
        break;
    }

    console.log(i); // will output number 0 until 5
}


// continue, skip loop

let b = 1; 

do {
    b++;
    if (b % 2 === 0) {
        continue; // will skip to the next iteration
    }

    console.log(`${b} is odd`);
} while (b < 10);

Arrays

const sequence = [1, 2, 3, 4, 5];

console.log(sequence.length); // output: 5

// slicing array
console.log(sequence.slice(0, 2)); // output [1, 2];
console.log(sequence.slice(2, 3)); // output [3];

// splice array
sequence.splice(0, 2);
console.log(sequence) // output [3, 4, 5];

// append new element
sequence.push(6);
console.log(sequence); // output [3, 4, 5, 6];

// shifting & popping element
console.log(sequence.shift()); // output 3
console.log(sequence.pop()); // output 6
console.log(sequence); // output [4, 5]

// concatenating array
const newSequence = sequence.concat([6, 7, 8]);
console.log(sequence); // output [4, 5]
console.log(newSequence); // output [4, 5, 6, 7, 8]

Manipulating arrays

// mapping array

const sequence2 = [0, 1, 2, 3, 4];
const newArray = [];

for (let i = 0; i < sequence2.length; i++) {
    newArray.push(sequence2[i] * 3);
}

// roughly equal with
const newArray2 = sequence2.map(item => item * 3);

// reducing array

const sum = 0;

for (let i = 0; i < sequence2.length; i++) {
    sum += sequence2[i];
}

// roughly equal with

const sum2 = sequence2.reduce((acc, value) => acc + value, 0);

Filtering array

// mapping array

const sequence3 = [0, 1, 2, 3, 4];
const even = [];

for (let i = 0; i < sequence3.length; i++) {
    if (sequence3[i] % 2 === 0) {
        even.push(sequence3[i]);
    }
}

// roughly equal with
const even2 = sequence2.filter(item => item % 2 === 0);

Objects

const sound = 'Meh';
const cat = {
    sound: 'Meow',
    say() {
        console.log(this.sound);
    },
    saying: () => console.log(this.sound);
};

cat.say();
cat.saying(); // guess the output

// you can have nested object

const dog = {
    sound: 'Ruff',
    say() {
        console.log(this.sound);
    },
    hunger: {
        level: 90,
        since: '2 hours ago',
    },
};

Objects

const animal = {
    sound: '',
    name: '',
    say() {
        console.log(this.sound);
    },
    greet() {
        console.log(`Hi, I'm ${this.name}`);
    },
};

// both cat and dog have the same prototype, that is animal

const cat = Object.create(animal);
cat.sound = 'Meow';
cat.name = 'Fluf';

cat.say();
cat.greet();

const dog = Object.create(animal);
dog.sound = 'Ruff';
dog.name = 'Randal';

dog.say();
dog.greet();

Function

// impure function

let i = 0;

function increment() {
    i = i + 1;
    return i;
}

const result = increment();
console.log(result === i) // true

// pure function

function sum(a, b) {
    return a + b;
}

console.log(sum(1, 2) === 3) // true

// no return value, is it?

function noreturn () { }

console.log(typeof noreturn() === 'undefined'); // gues the output

Function

// anonymous function

const add = function (a, b) {
    return a + b;
}

add(1, 2);

const add = (a, b) => a + b;
const random = () => {
    const rand = Math.random();
    return rand * 3;
};

// named function

function add2(a, b) {
    return a + b;
}

Function

function add(a) {
    return function curried(b) {
        return a + b;
    };
}

const addBy3 = add(3);
console.log(addBy3(4) === 7); // true
console.log(addBy3(8) === 11); // true


function catFactory(name) {
    return {
        name: name,
        sound: 'Meow',
    };
}

const hikari = catFactory('Hikari');
console.log(hikari.sound);

Function

function say() {
    console.log(this.sound);
}

say(); // guess the output

var sound = 'Meow';

say(); // guess the output

const boundSay = say.bind({ sound: 'Ruff' });

boundSay(); // guess the output

// Let's do this with arrow function

const sayArrow = () => console.log(this.sound);

sayArrow(); // guess the output

const boundSayArrow = sayArrow.bind({ sound: 'Haha' });

boundSayArrow(); // guess the output

Function

// Constructor

function Cat() {
    this.sound = 'Meow';
}

Cat.prototype.say = function () {
    console.log(this.sound);
};

var myCat = new Cat(); // wait, what?
myCat.say();

Javascript is weird, isn't it?

Let's Node

Filesystem Module

const fs = require('fs');

fs.writeFile('newfile.txt', 'Hello fs!', (err) => {
    if (err) {
        console.error('Shit happens', err);
    } else {
        console.log('Written to file successfully');
    }
});

fs.readFile('newfile.txt', (err, content) => {
    if (err) {
        console.error('Failed to read file', err);

        return false;
    }

    const contentString = content.toString();
    console.log('Content: ' + contentString);
});

DyCode Bootcamp - Node.js Intro Day 1

By Alwin Arrasyid

DyCode Bootcamp - Node.js Intro Day 1

  • 1,179