Installation de Node.js

Lors de l'installation de Node.js, vous aurez les binaires :

  • npm : Node Package Manager, le gestionnaire de packets pour Node. Le site npm pour chercher des packages
  • node : le binaire de Node
$ node -v
v12.18.3     v14.9.0

$ npm -v
6.14.6       6.14.8

Download for Windows (x64) 14.15.0 LTS : Recommended For Most Users 15.2.0 Current : Latest Features

Les versions de NodeJS

  • Node.js 08 : 2017-05
  • Node.js 10 : 2018-04
  • Node.js 12 : 2019-04
  • Node.js 14 : 2020-04
  • Node.js 15 : 2020-10 (non LTS)
  • Node.js 16 : 2021-04

A partir de la version 14, le format local (i18n/intl) est valable : Internationalization support : Intl : system-icu/small-icu : partial (English-only) (voir intl_number_format.js)

const number = 123456.789;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
console.log(new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(number));

//Node v12  € 123,456.79
//Node v14  123 456,79 €
//FF        123 456,79 €

console.log(new Intl.NumberFormat('fr-FR', { 
    //style: 'currency', 
    //currency: 'EUR' 
}).format(number));

//Node v12  123,456.789
//Node v14  123 456,789
//FF        123 456,789

console.log(Intl.NumberFormat.supportedLocalesOf('fr'));
//Node v12  []
//Node v14  [ 'fr' ]
//FF        Array [ "fr" ]

Obtenir la version de NodeJs par programmation

How to get node version programmatically?

console.log(process.version); // juste la version : v14.9.0
console.log(process.versions); // la version et ses dépendances :
// {
//  node: '14.9.0',
//  v8: '8.4.371.19-node.13',

NodeJs online

En 2020, je n'ai trouvé aucun compilateur Node en version 14 ou 15. au mieux la version 12 de 2019. Est ce que Node et en perte d'intérêt ?...

Repl.it - Node.js Online Compiler v12.18.3

NodeJS program - myCompiler v12.13.0

Online NodeJS IDE v12.12.0

Online Node Compiler v6.11.2

En vrac .....................

Node.js vs TypeScript sur Google Trends

Error handling in Node.js

Express et son API

  • Express-approved middlewares to use in your API body-parser, cookie-session, cors, morgan, multer, serve-static, session
    • session storing the session data within a large number of stores mecache : connect-memcached, connect-memjs sql : connect-session-knex, connect-session-sequelize, express-mysql-session, ...

Les ressources de pierre-giraud sur le développement web, et son Cours complet (2020) pour Apprendre à coder en JavaScript

NPM

Les modules installés globalement :

npm list -g --depth=0

Mais voyez également les alternatives pour How to list npm user-installed packages? : - npm-gui (npm install -g npm-gui; cd c:\votre-dossier-projet; npm-gui localhost:9000; http:\\localhost:9000) - NPM Desktop manager

Problème de dépendances installée localement ou globalement avec l'option -g

Pour résoudre les erreurs "Error: Cannot find module xxx", et que vous avez installez ce module globalement, dans votre projet faite un lien avec : "npm link xxx"

D:\dev\js\node-mysql-webfor>npm install -g express sequelize body-parser mysql mysql2
+ body-parser@1.19.0
+ mysql2@2.1.0
+ express@4.17.1
+ mysql@2.18.1
+ sequelize@6.3.4
added 29 packages from 28 contributors and updated 4 packages in 3.323s

D:\dev\js\node-mysql-webfor>node app index.js
Error: Cannot find module 'express

D:\dev\js\node-mysql-webfor>npm link express
D:\dev\js\node-mysql-webfor\node_modules\express -> C:\Users\ryzen\AppData\Roaming\npm\node_modules\express

Les modules

async await Promise (Pending, Resolved, Rejected) Promise.all()

developer.mozilla.org

  • async function
  • L'opérateur await permet d'attendre la résolution d'une promesse (Promise). Il ne peut être utilisé qu'au sein d'une fonction asynchrone (définie avec l'instruction async function).
  • L'objet Promise (pour « promesse ») est utilisé pour réaliser des traitements de façon asynchrone.

DOC

ESDoc is a good documentation generator for JavaScript.

ORM

  • Sequelize is a promise-based Node.js
  • TypeORM is an ORM that can run in NodeJS, ... and can be used with TypeScript and JavaScript ... TypeORM supports both Active Record and Data Mapper patterns ... influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.

Connecteurs MySQL et MariaDB

2018 A Tale of Two JSON Implementations - MySQL and MariaDB X DevAPI / Document Store : Seul MySQL a le magasin de documents.

Une tentative de connexion à un serveur MariaDB, vous retournera l'erreur : [Error: The server connection is not using the X Protocol. Make sure you are connecting to the correct port and using a MySQL 5.7.12 (or higher) server intance. |https://stackoverflow.com/questions/50254769/mysql-xdevapi-with-node-js-the-server-connection-is-not-using-the-x-protocol/50359438]

Sequelize

Sequelize createdAt and updatedAt, disabling timestamps from your mode

sequelize.define('modelName', {
// props
},{
    timestamps: false
})

Un tuto nodejs express sql

Créer un CRUD à l'aide de la base de données NodeJS ExpressJS MySQL :

  • body-parser : utilisé pour analyser la requête entrante du client final.
  • mysql : pilote Node JS pour connecter MySQL et effectuer des opérations CRUD.
  • ejs : est un moteur de création de modèles et il est utilisé pour rendre des pages HTML au client final
  • nodemon : package facultatif et installé globalement, qui nous aide à écouter les modifications apportées aux fichiers et à redémarrer automatiquement le serveur d'applications.
npm init
npm install --save express mysql body-parser ejs
npm install -g nodemon

Editez vos fichier app.js, puis exécutez :

nodemon app 
(ou)
npm start

Votre serveur écoute sur : http://localhost:3000/

D:\dev\js\crud_express_mysql>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (crud_express_mysql) crud
version: (1.0.0)
description:
entry point: (index.js) app.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\dev\js\crud_express_mysql\package.json:

{
  "name": "crud",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) yes

D:\dev\js\crud_express_mysql>npm install --save express mysql body-parser ejs
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN crud@1.0.0 No description
npm WARN crud@1.0.0 No repository field.

+ express@4.17.1
+ mysql@2.18.1
+ ejs@3.1.5
+ body-parser@1.19.0
added 74 packages from 54 contributors and audited 75 packages in 5.21s
found 0 vulnerabilities


D:\dev\js\crud_express_mysql>npm install -g nodemon
C:\Users\ryzen\AppData\Roaming\npm\nodemon -> C:\Users\ryzen\AppData\Roaming\npm\node_modules\nodemon\bin\nodemon.js

> nodemon@2.0.4 postinstall C:\Users\ryzen\AppData\Roaming\npm\node_modules\nodemon
> node bin/postinstall || exit 0

Love nodemon? You can now support the project via the open collective:
 > https://opencollective.com/nodemon/donate

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules\nodemon\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ nodemon@2.0.4
added 120 packages from 54 contributors in 7.234s

D:\dev\js\crud_express_mysql>npm start
npm ERR! missing script: start

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ryzen\AppData\Roaming\npm-cache\_logs\2019-05-23T19_10_56_789Z-debug.log

D:\dev\js\crud_express_mysql>nodemon app
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
Server is running at port 3000

Attention, à l'injection SQL non traitée dans ce tutoriel, en mettant à jour un utilisateur avec une simple quote "Toto l'injecteur", cela fait :

  • planter l'exécution de la requête
  • qui s'enchaine sur un plantage et arrêt du serveur node à cause de la gestion des erreurs (throw err; // Rethrow non-MySQL errors), voyez un code corrigeant ce comportement : throw err; // Rethrow non-MySQL errors

Pour ne plus planter :

Il ne faut pas renvoyer l'erreur

if(err) throw err;    // throw err; // Rethrow non-MySQL errors

mais écouter les erreurs sur l'objet query :

let query = connection.query(sql,(err, results) => {
    //   if(err) throw err;    // throw err; // Rethrow non-MySQL errors
      res.redirect('/');
    // });
    }).on('error', function(err) {  // pour : throw err; // Rethrow non-MySQL errors
        console.log("[mysql error]",err);
    });
Server is running at port 3000
Database Connected!
D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'injecteur',  email='ff@gg.hh',  phone_no='+336' where id =1' at line 1
    at Query.Sequence._packetToError (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
    at Query.ErrorPacket (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
    at Protocol._parsePacket (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Protocol.js:38:16)
    at Socket.<anonymous> (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\Connection.js:88:28)
    at Socket.<anonymous> (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\Connection.js:526:10)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    --------------------
    at Protocol._enqueue (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Connection.query (D:\dev\js\crud_express_mysql\node_modules\mysql\lib\Connection.js:198:25)
    at D:\dev\js\crud_express_mysql\app.js:77:28
    at Layer.handle [as handle_request] (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\layer.js:95:5)
    at D:\dev\js\crud_express_mysql\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\index.js:335:12)
    at next (D:\dev\js\crud_express_mysql\node_modules\express\lib\router\index.js:275:10) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'injecteur',  email='ff@gg.hh',  phone_no='+336' where id =1' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "update users SET name='Toto l'injecteur',  email='ff@gg.hh',  phone_no='+336' where id =1"
}
[nodemon] app crashed - waiting for file changes before starting...
rs
[nodemon] starting `node app.js`
Server is running at port 3000
Database Connected!

Les IDE

  • Visual Studio Code (shortcuts)
  • Microsoft Visual Studio

Autres tuto ou code

developpez.com

openclassrooms.com

Cours et tutos complets survolant l'ensemble :

riptutorial.com

tutorialkart.com

-- TypeScript

TypeScript: Playground - An online editor for exploring TypeScript and JavaScript

tutorialspoint TypeScript - Classes

How To Compile TypeScript On The Command Line

Converting Existing JavaScript to TypeScript

SQL :

IDE :

CODE et NOTES :

-- Tracer How can I get the full object in No...'?|https://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-jss-console-log-rather-than-object|en]

https://nodejs.org/api/console.html#console_console_dir_obj_options console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion

https://nodejs.org/api/util.html#util_util_inspect_object_options console.log(util.inspect(myObject, {showHidden: false, depth: null})) // alternative shortcut console.log(util.inspect(myObject, false, null, true /* enable colors */))

How to use util.inspect

-- DEBUG

Debugging Node.js with Chrome DevTools

node --inspect index.js

  1. Break on the first statement of the script with --inspect-brk

node --inspect-brk index.js

chrome : about:inspect

Debugging Guide

Debugger

-- PROCESS

How to Exit in Node.js

process.on('exit', function(code) {

   return console.log(`About to exit with code ${code}`);

});

-- Express

Express Route Tester

Générateur d’applications Express

Express Web Framework (Node.js/JavaScript)

Template engines : EJS, Pug, ...

Using template engines with Express

-- Express RENDER

Express.js res.render() Function

How to use render function in Response

res.render('books/form.pug', {

res.render('index', {

Render HTML In Node.js

-- View Engines

Node js View Engine: Try out some of the most popular EJS, Pug, Hbs (Handlebars.js)

What is Pug.js (Jade) and How can we use it within a Node.js Web Application?

Développer et tester l’interface HTML avec Node.js et Pug (ancien Jade)

Découverte du langage Pug (Jade) pour développer des interfaces HTML avec VSCode ou Geany

  • EJS Embedded JavaScript templating
# with NPM command
npm install -g express-generator
# create project
express --view=ejs nodejs-crud
# go to the project folder:
cd nodejs-crud
# to send flash message:
npm install express-flash --save
# to make session like PHP:
npm install express-session --save
# to send PUT and DELETE requests:
npm install method-override --save
# driver to connect Node.js with MySQL:
npm install mysql --save
<%# commented out code %>
<%/* multiple lines commented out code*/%>

EJS echo

Pour faire un echo avec EJS

// the same as echo string
__append(string)     

<input type="radio" name="is_public" value=1 <% if(my_data.is_public){ __append('checked') } %> />Public

EJS uses moment lib

import express = require('express');

import * as moment from 'moment';
import 'moment/locale/fr';

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'pug');
app.set('view engine', 'ejs')

app.locals.moment = moment;

et dans votre vue .ejs

<input type="text" name="date" placeholder="jj/mm/aaaa" value="<%= moment(monobjet['date']).format('L'); %>" />

riptutorial :

  • Pug est un moteur de gabarit riche en fonctionnalités, robuste et élégant. Il a été influencé par Haml et implémenté avec JavaScript pour Node.js et les navigateurs
  • apprenez pug.pdf

EJS vs Pug

Pug VS EJS

EJS vs pug (Jade)

How to build your first Node.js website with Express and Pug

-- Autres

DanWahlin/NodeJSWorkshop Node.js Samples

Un équivalent à PhpMyAdmin en Node.js : Express Admin - simov/express-admin

JS JavaScript

javascript.info : The JavaScript language

Arrow

Arrow function expressions (Fonctions fléchées)

Arrow Function

hello = function() { // Before
  return "Hello World!";
} 
hello = () => { // With Arrow Function
  return "Hello World!";
} 
hello = () => "Hello World!"; // Arrow Functions Return Value by Default
hello = (val) => "Hello " + val; // Arrow Function With Parameters
hello = val => "Hello " + val; // Arrow Function Without Parentheses:

Arrow functions, the basics

Nullish coalescing operator '??'

Attention, c'est opérateur, n'est disponible qu'a partir de Node.js >= 14.0.0

Nullish coalescing operator '??'

Nullish coalescing operator (??)

Operator precedence

// set height=100, if height is null or undefined
height = height ?? 100;

How to use the new Nullish Coalescing operator in JavaScript

-- TypeSript et Node

Using TypeScript with the MySQL Database

Using TypeScript with Node.js and Express

Add TypeScript

Let’s add two libraries to the development server as devDependencies.

   typescript is a core library that helps to compile the TypeScript code to valid JavaScript
   ts-node is a utility library that helps to run a development server written using TypeScript directly from the terminal

There is a GitHub repository that maintains the TypeScript type definitions to use directly in Node.js and other JavaScript projects without bothering to define these types from scratch. This repository is called DefinitelyTyped. DefinitelyTyped - The repository for high quality TypeScript type definitions.

Create an Express server with .ts extension Watching file changes with nodemon "start": "nodemon index.ts", Compile a TypeScript project "build": "tsc --project ./",

How (and why) you should use TypeScript with Node and Express. andregardi/ts-express

npm install express -s npm install @types/express -s

Express and Typescript packages are independent. The consequence of this is that Typescript does not “know” types of Express classes. There is a specific npm package for the Typescript to recognize the Express types : @types/express

npm run tsc node build/app.js

Running TypeScript without transpiling

npm install ts-node-dev -s

"scripts": {

   "tsc": "tsc",
   "dev": "ts-node-dev respawn transpileOnly ./app/app.ts",
   "prod": "tsc && node ./build/app.js"

},

npm run dev npm run prod

-- Exercices

https://nodeschool.io/#workshoppers

Un Mölkky connecté avec Node JS et du Bluetooth Low Energy

-- Themes templates

-- Express - gestion des erreurs

Functional Error Handling with Express.js and DDD

How common approaches to handling errors fail to express domain concepts

  • (1) Return null
  • (2) Log and throw
  • A better approach to handling errors
  • Domain-Driven Design for the win : Errors are a part of the Domain layer in our clean/layered architecture

-- Express middleware

Express.js: Writing middleware