CodeLab

express().use(session({

by : 'Gautam' )}

Thanks to Newton-Circus for hosting!

Intro

Setup
Code

20-35 mins

10-15 mins

30-40 mins

90:00 mins

http://tinyurl.com/NEAN3

Javascript in Stack

  • Unify client-side and server-side code  
  • Promoting Non-Blocking Programming

Callbacks & Event Loop inbuilt

Reuse : Components & Resources 

Incredible fast platform 

Asynchronous Architecture

Scale code across developers, Work in sync!

Javascript in Stack

function getUser(id) {
    var user = db.query(id);
    return user;
}
 
console.log('Name: ' + getUser(432).name);

The function blocks until the database call is completed. This means the server is doing nothing but waiting until the function completes, ignoring other pending requests.

function getUser(id, callback) {
    db.query(id, callback);
}
 
getUser(432, function (user) {
    console.log(user.name);
});

console.log('Done');

VS

Output :

 

(1) Done

(2) Value(user.name)

Sync

A-Sync

Javascript in Stack

function add(list, title, position) {
    // Add new item to 'items' store
    var item = db.insert('items', { list: list, title: title });
    //  Set position if requested
    if (position !== null) {
        var sort = db.get('items.sort', list);
        addToListAt(sort, item.id, position);
        db.update('items.sort', sort);
    }
    // Perform final processing
    var result = { status: 'ok', time: (new Date()).getTime() };
    return result;
}
function add(list, title, position, callback) {
    // Add new item to 'items' store
    db.insert('items', { list: list, title: title }, function (item) {
        //  Set position if requested
        if (position !== null) {
            db.get('items.sort', list, function (sort) {
                addToListAt(sort, item.id, position);
                db.update('items.sort', sort, function () {
                    finish(item.id);
                });
            });
        }
        else {
            finish(item.id);
        }
    });
    function finish(id) {
        // Perform final processing
        callback({ id: id, status: 'ok', time: (new Date()).getTime() });
    }
}

vs

Blocking Code style

Not so Blocking Code style

  • Add new item to store
  • Set position if requested
  • perform final processing

Logic

  • Divided output logic into simpler functions
  • Callback function used

No -Callback & Event Loop

Callback & Event Loop

Javascript in future ?

  • Functional Programming
  • Dynamic Objects & Prototypal Inheritance
  • JS is the internet
  • Every computer in the world has at-least one JS interpreter.
  • All those pages cannot be neglected so its not going anywhere. Yes but we can improve it.
  • High level language not assembly i.e you can understand its code. 
  • Makes it easy to adapt for developers
  • I.e treats computation as evaluation of Mathematical functions and avoids changing state & mutable data.
  • Output depends upon arguments then input of function.
  • Save you lines of codes - thats what every developer wants right? 
  • Object-Oriented Programming without classes (and without endless hierarchies of classes) allows for fast development (create objects, add methods, and use them)
  • Reduces refactoring time during maintenance tasks by allowing the programmer to modify instances of objects instead of classes. This speed and flexibility paves the way for rapid development.

NodeJS ?

  • Node.js is a platform for building fast and scalable network applications
  • It’s the preferred runtime environment for any JavaScript application with I/O access.

ExpressJS ?

  • Server componentization using 'middleware' : Define components on server. Inspired from 'Pipes' & 'Filters'.
  • Component is part of pipeline : Has Input & Output. Component modifies & delegates to next piece in pipeline. Last piece output is send to client.

Setup

$sudo apt-get install git
$sudo apt-get install build-essential
$sudo apt-get install wget
$ wget source_nodejs_path_from_website
$ tar xvf file_name_nodejs.tar.gz
$ pushd folder_extracted
$ ./configure
$ make
$ sudo make install

Requirements 

GET Source-file

Make

$ node --version
$ node
$npm install -g express
$npm install -g express-generator
$express -h
$express app_name
$cd app_name
$npm install 
$node app.js

Check & Run

Before we start !

$git clone https://github.com/ga1989/fileupload-nodejs.git

$cd fileupload-nodejs
$npm install 
$ node app.js

//localhost:3031

or

http://fileu-156165.apse1.nitrousbox.com:3031/

Code 

$express fileU2
$cd fileU2
$npm install
$npm install nodemon -g
{
  "name": "fileU2",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.9.0",
    "body-parser": "~1.8.1",
    "cookie-parser": "~1.3.3",
    "morgan": "~1.3.0",
    "serve-favicon": "~2.1.3",
    "debug": "~2.0.0",
    "jade": "~1.6.0",
    "busboy" : "latest",
    "connect-busboy" : "latest",
    "fs-extra" : "latest",
    "fs" : "latest"
  }
}

Step 1

Step 2: Package.json

FileUpload

Module

"Lets not do Hello world"

Code​ 


//Part 1 : Defining and calling npm

var express = require('express');  
var busboy = require('connect-busboy');
var path = require('path');  
var fs = require('fs-extra'); 
var fsold = require('fs');
var app = express();

// Part 2 : App configurations
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));


//Part 3 : Routes

app.get('/upload', function(req, res){
 
});

app.post('/upload', function (req, res, next) {

    });

//Part 4 : Running server

var server = app.listen(3031, function() {
    console.log('Listening on port %d', server.address().port);
});

Part 1

Part 2

Part 3

Part 4

app.js

  • When http://example.com/resource/IDVALUE
  1. GET : Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
  2. PUT : Update the addressed member of the collection or create it with the specified ID.
  3. POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
  4. DELETE: Delete the addressed member of the collection.
  • When http://example.com/resource
  1. GET : List of Members of the collection, complete with their member URIs for further navigation.
  2. PUT : Replace entire collection with another collection.
  3. POST: Create a new entry in the collection where the ID is assigned by the collection.
  4. DELETE: Delete the entire collection.

Code​ 

RestFul resources/Routes

Code

app.post('/upload',fn());

app.post('/upload', function (req, res, next) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

            console.log ("filename: " + filename);
            console.log ("fieldname: " + fieldname);
            console.log ("encoding: " + encoding);
            console.log ("mimetype: " + mimetype);

            //Path where file will be uploaded with original filename
            fstream = fs.createWriteStream(__dirname + '/public/file/' + filename);
            file.pipe(fstream);

            fstream.on('close', function () {    
                console.log("Upload Finished of " + filename);              
                res.redirect('back');           //where to go next
            });        });    });

POST

  • When form pushes start .on()
  • Push to upload folder
  • Confirm upload complete and exit

Code

app.get('/upload', function(req, res){

        fs.readdir( __dirname + '/public/file/', function(err, files) {

            if (err) {

                res.send(err);
            }
            res.json(files); // return all files in JSON format
        });
 
});

app.get('/upload',fn());

GET

  • Read the directory for path
  • Render files as JSON
<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>Simple FileUpload Module</title>
</head>

<body>

         <a href="/upload"> Implement the GET for /Upload</a>

         <br>

        <form method='post' action='/upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>

        </form>
 </body>
</html>

Code

<form></form>

Just another HTML form

Code

Output

Thanks!

More complicated projects :

CodeLab - Node

By Gautam Anand

CodeLab - Node

Singapore NEAN Meetup#3

  • 1,541
Loading comments...

More from Gautam Anand