node.js – modules – NPM

This is a practical course using node.js and a localhost development environment.

INSTALL THE LOCAL ENVIRONMENT

For local development I use Laragon (https://laragon.org/), it is really well organized, easy to use and portable.

Download Laragon – Full, is has already the latest node.js stable edition inside, double click the Laragon icon and Start all services, if you are under Windows you will see a Windows Command Processor message, ignore it.

WHAT IS NODE JS MODULES AND NPM

Node.js is organized in modules, a module is like a javascript library that do something.
The core of Node.js has only few modolus (built-in module), to do foundamental operations like:
– HTTP transfer data
– File System management
– URL parsing
– Event fire and listen
etc…

If you need more you have to install other modules, for example to upload files, send emails, connect to a database. To live happy you have to use NPN (Node Package Manager https://www.npmjs.com/) that is the official ‘repository’ for Node.js modules, NPM works great because it install all dependencies too 😀

USE OF NPM – TEST INSTALLATION

1. Start Laragon (or your local environment), and run all services

2. Create a folder inside laragon/www/myapp

3. Start the terminal in Laragon ‘Cmder’, put the terminal inside myapp folder you will see in the command prompt: laragon\www\myapp then you are inside the right folder

4. type: npm -h
If you see the help instructions of npm it means that npm is installed and runs correctly, nice!

USE OF NPM – SEARCH MODULES

5. type: npm search mysql
You will see all the list of modules to manage mysql, it is clear, the syntax is npm search [keyword]

USE OF NPM – INSTALL MODULES

6. type: npm istall mysql
Go inside laragon/www/myapp npm has created:

a. folder ‘node_modules’ and inside it you can find mysql module and all dependencies.
NOTICE: the module is installed ONLY in the local folder of your app, if you have another app you have to install again for every app you create.

b. package-lock.json that contains the informations about downloaded modules

USE OF NPM – CODE WITH MODULES

7.

// load modules in code
var mysql = require('mysql'); 

// use modules functions
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

nodejs

USE OF NPM – UPDATE MODULES

Super easy! Type: npm update
NOTICE: this command delete the old module and install the new one, pay attention to compatibility between old and new packages

USE OF NPM – PUBLIC YOUR MODULES

You can publish for free your own modules and become famous :) give a look to https://docs.npmjs.com/cli/publish

By |JavaScript, NodeJS, Web Design|Commenti disabilitati su node.js – modules – NPM

JS Redirection – IOS – Android

JS Redirection – IOS – Android

Create in the same folder:
– mobile-detector.html
It this the javascript that detects the device type
– ios.html
The page for IOS devices
– android.html
The page for Android devices
– error.html
An Error page

mobile-detector.html


<!DOCTYPE html>
<html>
<head>
 
<script type="text/javascript">
// #######################################################
// Mobile JS Redirect
// Don't Break My b***s - Gimme Code! Project                                           
// Author: Andrea Tonin - http://blog.lucedigitale.com                                 
// This code come with absolutely no warranty                                            
// If you use this code in your project please give a link to http://blog.lucedigitale.com 
// Thanks in advance                                                                       
// #######################################################
 
var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }

    };



if ( isMobile.Android() ) {
        document.location.href = "android.html";
    }
else if(isMobile.iOS())
	{
	document.location.href="ios.html";
	}
else
    {
    document.location.href="error.html";
    }
 
</script>
 
</head>
 
<body>
<center>
<br>
<b><h1>You are being redirected to other site.</h1>
<br>
<br>
<h1>If you are not redirected within 4 seconds</h1></b>
<br>
<h1><a href="android.html">ANDROID HERE</h1></a>
<h1><a href="ios.html">IOS HERE</h1></a>
</center>
</body>
 
</html>

ios.html


<!DOCTYPE html>
<html>
 
<head>
</head>
 
<body>
<!-- Questo è un commento, non viene renderizzato dal browser -->
<h1>IOS!</h1>
</body>
 
</html>

android.html


<!DOCTYPE html>
<html>
 
<head>
</head>
 
<body>
<!-- Questo è un commento, non viene renderizzato dal browser -->
<h1>Android!</h1>
</body>
 
</html>

error.html


<!DOCTYPE html>
<html>
 
<head>
</head>
 
<body>
<!-- Questo è un commento, non viene renderizzato dal browser -->
You need an Android or IOS device!
</body>
 
</html>

By |JavaScript, Web Design|Commenti disabilitati su JS Redirection – IOS – Android

PHP MySQL code to extract data from MySQL table and display as JSON

MySQL -> PHP -> JSON Layer -> JS/HTML

To prevent database password sniffing you must not get a direct access to database (sending database access datas).
The best way is to call a PHP engine and after, the PHP engine will render simple JSON data structure.
In the end you can use JScript to write, on the fly, the final HTML code.

json structure

We need store this simple datas:

Users:

Andrea Tonin January, 12 2012
Riccardo Santato April, 28 2010

We will create this json structure:

{"users":[
        {
            "firstName":"Andrea",
            "lastName":"Tonin",
            "joined": {
                "month":"January",
                "day":12,
                "year":2012
            }
        },
        {
            "firstName":"Riccardo",
            "lastName":"Santato",
            "joined": {
                "month":"April",
                "day":28,
                "year":2010
            }
        }
]}

Create database

Open phpMyAdmin

On the top localhost> mydatabase

Use phpMyAdmin to create:

Left Column> ‘Crea tabella’> MyISAM

Table name: ‘users’

PhpMyAdmin> In Alto> linguetta Struttura> aggiungere i campi

Campo: id
Tipo: INT
Lunghezza: 20
Predefinito: Nessuno
Null: deselezionato
Indice: PRIMARY
AUTO_INCREMENT: selezionato

Campo: firstName
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: lastName
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: month
Tipo: VARCHAR
Lunghezza: 20
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: day
Tipo: INT
Lunghezza: 2
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: year
Tipo: INT
Lunghezza: 4
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

The final result inside phpMyAdmin:

mysql-0009

PhpMyAdmin> In Alto> linguetta Inserisci>

Aggiungere i campi:

Andrea Tonin January, 12 2012
Riccardo Santato April, 28 2010

colonna di sinistra PhpMyAdmin> click su ‘users’>

mysql-0010

PHP json translator – php-json.php

<?php
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="users"; //indicate la tabella presente nel database a cui si deve collegare 
  
// Connetti al server e seleziona il database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("DB non connesso");
 
// JSON TRANSLATOR CODE START ###################################
 
$sql = "select * from users"; //indicate la tabella presente nel database a cui si deve collegare 
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['users'][]=$row;  //indicate la tabella presente nel database a cui si deve collegare 
}
}
mysql_close($db_name);
echo json_encode($json); // json_encode() PHP Function
 
// JSON TRANSLATOR CODE END ####################################
?> 

Notice:

echo json_encode($json); // json_encode() PHP Function

If you execute php-json.php, you will see:

{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}

JScript Render – js-json.php

<!DOCTYPE html>
 
<html>
<head> 
</head>
 
<body>

    <!-- Write with PHP include function -->
    Write with PHP include function: <br>
    <?php include("php-json.php"); ?>
     
    <script>
	// Write with Javascript
	var jsoncontent='<?php include("phpjson.php"); ?>';
	document.write('<br>Write with JavaScript - simple variable:<br>');
	document.write(jsoncontent);
    </script>
	
</body>
 
</html>

If you execute js-json.php, you will see:

Write with PHP include function:
{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}
Write with JavaScript – simple variable:
{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}

You can store the data inside a javascript object:

<!DOCTYPE html>
  
<html>
<head> 
</head>
  
<body> 
    <script>
    // Write with Javascript
    var jsoncontent='<?php include("php-json.php"); ?>';
    var obj = JSON.parse(jsoncontent);
    alert(JSON.stringify(obj, null, 4));
    </script>   
</body>
  
</html>

Notice: JSON.stringify function to print out Javascript objects

The result is:
json-0001

By |JavaScript, JSON, MySQL, PHP, Web Design|Commenti disabilitati su PHP MySQL code to extract data from MySQL table and display as JSON

Unity – Scripting – Debug

Videogames Development – Unity – Debug.Log

Logs message to the Unity Console.

Statements:

// Message with a link to an object.
Debug.Log ("Hello", gameObject);

// Message using rich text.
Debug.Log("<color=red>Fatal error:</color> AssetBundle not found");

SCRIPT

MAIN TOP MENU> ASSETS> CREATE> Javascript, type the name ‘GetMousePosition’

Assets> GetMousePosition> Inspector> ‘Open…’ button

Write:

#pragma strict

function Start () {

}

function Update () {
	var mouse = Input.mousePosition;
        Debug.Log(mouse);
		
	}

Create an Object inside the Hierarchy ‘MyObject’

Assets> DRAG AND DROP ‘GetMousePosition’ script over Hierarchy> MyObject

Play> move the mouse, look at the BOTTOM OF THE SCREEN, you will see the coordinates as: (536.0, 583.0, 0.0)

By |JavaScript, Unity3D, Video Games Development|Commenti disabilitati su Unity – Scripting – Debug

JavaScript Calculator – Basic

JavaScript Calculator – Basic

By |JavaScript, Web Design|Commenti disabilitati su JavaScript Calculator – Basic