Category Archives: JavaScript

JavaScript 83 – conclusioni

Continuo da qui.

OK, finito l’esame dell’ottimo Eloquent LavaScript di Marijn Haverbeke 🚀 😊
Ottimo. Consigliatissimo. Il sottotitolo del libro è A modern introduction to programming. Vero ma io sono della vecchia scuola e JavaScript mi lascia un po’ perplesso come linguaggio, cosa nota e lollata, per esempio qui.

Ma sono solo io; il mondo la pensa diversamente. Nelle classifiche dei linguaggi che si pubblicano periodicamente JavaScript risulta sempre tra i primi. E io mi sono deciso a esaminarlo perché viene usato a Stanford.

La mia carenza, quella che m’impedisce di giudicarlo imparzialmente è che lo vedo come linguaggio tradizionale, da desktop. Cioè non lui ma Node (o equivalenti). Ignorando il Web e il suo ecosistema. Me l’hanno fatto notare tanti che non sanno che sono vecchio e ormai fuori dal mondo. Lo so che con CSS, HTML e qualcos’altro è quello che si usa adesso. OK, ci sarebbe anche il PHP (no, non voglio guardarlo). E tutti usano un’IDE come si deve. Probabilmente con Windows.

OK, magari qualcuno (l’amico PLG? ma dove lo trova il tempo?) potrebbe dire qualcosa, chissà… 😯

Un po’ di risorse le trovate sulla pagina Manuali e documenti di questo blog.
Node nella pagina citata è trattato separatamente (sono recidivo nel mio bias 😡).

Ah! un’ultimissima cosa di Node, per Linux. Riprendendo l’esempio di conversione dei fradi Fahrenheit in Celsius per renderlo eseguibile (OK, lo so, lo so ma repetita  juventus  juvant).

Dov’è Node:

Modifico lo script inserendoci la shebang, dev’essere la prima riga,

#!/usr/bin/node

if (process.argv.length > 2) {
  var F = process.argv[2];
  
  var C = (F - 32) * 5 / 9;
  C = C.toFixed(0);  
  console.log(F, "°F ->", C, "°C"); 
}

e lo rendo eseguibile

Per finire si può togliere l’estensione .js (conviene farne una copia, non si sa mai, metti che…) e per eseguirlo da una directory qualunque basta metterlo in una directory contenuta nella path, di solito ~/bin

:mrgreen:

Annunci

JavaScript 82 – Node.js – 4

Continuo da qui, copio qui.

Streams
Una parola antica, non usata nel mondo Windows, ma vedremo che sono in pratica files.

We have seen two examples of writable streams in the HTTP examples—namely, the response object that the server could write to and the request object that was returned from http.request.

Writable streams are a widely used concept in Node interfaces. All writable streams have a write method, which can be passed a string or a Buffer object. Their end method closes the stream and, if given an argument, will also write out a piece of data before it does so. Both of these methods can also be given a callback as an additional argument, which they will call when the writing to or closing of the stream has finished.

It is possible to create a writable stream that points at a file with the fs.createWriteStream function. Then you can use the write method on the resulting object to write the file one piece at a time, rather than in one shot as with fs.writeFile.

Readable streams are a little more involved. Both the request variable that was passed to the HTTP server’s callback function and the response variable passed to the HTTP client are readable streams. (A server reads requests and then writes responses, whereas a client first writes a request and then reads a response.) Reading from a stream is done using event handlers, rather than methods.

Objects that emit events in Node have a method called on that is similar to the addEventListener method in the browser. You give it an event name and then a function, and it will register that function to be called whenever the given event occurs.

Readable streams have "data" and "end" events. The first is fired every time some data comes in, and the second is called whenever the stream is at its end. This model is most suited for “streaming” data, which can be immediately processed, even when the whole document isn’t available yet. A file can be read as a readable stream by using the fs.createReadStream function.

The following code creates a server that reads request bodies and streams them back to the client as all-uppercase text:

var http = require("http");
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  request.on("data", function(chunk) {
    response.write(chunk.toString().toUpperCase());
  });
  request.on("end", function() {
    response.end();
  });
}).listen(8000);

The chunk variable passed to the data handler will be a binary Buffer, which we can convert to a string by calling toString on it, which will decode it using the default encoding (UTF-8).

The following piece of code, if run while the uppercasing server is running, will send a request to that server and write out the response it gets:

var http = require("http");
var request = http.request({
  hostname: "localhost",
  port: 8000,
  method: "POST"
}, function(response) {
  response.on("data", function(chunk) {
    process.stdout.write(chunk.toString());
  });
});
request.end("Hello server");

The example writes to process.stdout (the process’ standard output, as a writable stream) instead of using console.log. We can’t use console.log because it adds an extra newline character after each piece of text that it writes, which isn’t appropriate here.

Poi Marijn passa a costruire un semplice file server HTTP. Salto. Anche gli esercizi sono fuori dai miei interessi.

Il capitolo successivo è un progetto lungo, sul Web, salto anche questo.

Sono così giunto alla fine dell’esame elementare di JavaScript. Le concluioni? Prossimamente 😉

:mrgreen:

JavaScript 81 – Node.js – 3

Ian McRae

Continuo da qui, copio qui.

Il modulo del File System
One of the most commonly used built-in modules that comes with Node is the "fs" module, which stands for file system. This module provides functions for working with files and directories.

For example, there is a function called readFile, which reads a file and then calls a callback with the file’s contents (file rf.js):

var fs = require("fs");
fs.readFile("file.txt", "utf8", function(error, text) {
  if (error)
    throw error;
  console.log("The file contained:", text);
});

The second argument to readFile indicates the character encoding used to decode the file into a string. There are several ways in which text can be encoded to binary data, but most modern systems use UTF-8 to encode text, so unless you have reasons to believe another encoding is used, passing "utf8" when reading a text file is a safe bet. If you do not pass an encoding, Node will assume you are interested in the binary data and will give you a Buffer object instead of a string. This is an array-like object that contains numbers representing the bytes in the files (rfb.js).

var fs = require("fs");
fs.readFile("file.txt", function(error, buffer) {
  if (error)
    throw error;
  console.log("The file contained", buffer.length, "bytes.",
              "The first byte is:", buffer[0]);
});

A similar function, writeFile, is used to write a file to disk (wf.js).

var fs = require("fs");
fs.writeFile("graffiti.txt", "Node was here", function(err) {
  if (err)
    console.log("Failed to write file:", err);
  else
    console.log("File written.");
});

Here, it was not necessary to specify the encoding since writeFile will assume that if it is given a string to write, rather than a Buffer object, it should write it out as text using its default character encoding, which is UTF-8.

The "fs" module contains many other useful functions: readdir will return the files in a directory as an array of strings, stat will retrieve information about a file, rename will rename a file, unlink will remove one, and so on. See the documentation at nodejs.org for specifics (dir.js).

var fs = require("fs");

fs.readdir("./", function (err, files) {
  if (err) {
    throw err;
  }
  console.log(files);
});

Many of the functions in "fs" come in both synchronous and asynchronous variants. For example, there is a synchronous version of readFile called readFileSync( rfsync.js).

var fs = require("fs");
console.log(fs.readFileSync("file.txt", "utf8"));

Synchronous functions require less ceremony to use and can be useful in simple scripts, where the extra speed provided by asynchronous I/O is irrelevant. But note that while such a synchronous operation is being performed, your program will be stopped entirely. If it should be responding to the user or to other machines on the network, being stuck on synchronous I/O might produce annoying delays.

Il modulo HTTP
Another central module is called "http". It provides functionality for running HTTP servers and making HTTP requests.

This is all it takes to start a simple HTTP server (https.js):

If you run this script on your own machine, you can point your web browser at http://localhost:8000/hello to make a request to your server. It will respond with a small HTML page.

The function passed as an argument to createServer is called every time a client tries to connect to the server. The request and response variables are objects representing the incoming and outgoing data. The first contains information about the request, such as its url property, which tells us to what URL the request was made.

Marijn continua ma io salto, lascio la gestione Internet a chi ne sa più di me, o gli interessa di più 😜

:mrgreen:

JavaScript 80 – Node.js – 2

Continuo da qui, copio qui.

Moduli
Beyond the few variables I mentioned, such as console and process, Node puts little functionality in the global scope. If you want to access other built-in functionality, you have to ask the module system for it.

The CommonJS module system, based on the require function, was described in Chapter 10 [qui]. This system is built into Node and is used to load anything from built-in modules to downloaded libraries to files that are part of your own program.

When require is called, Node has to resolve the given string to an actual file to load. Pathnames that start with "/", "./", or "../" are resolved relative to the current module’s path, where "./" stands for the current directory, "../" for one directory up, and "/" for the root of the file system. So if you ask for "./world/world" from the file /home/marijn/elife/run.js, Node will try to load the file /home/marijn/elife/world/world.js. The .js extension may be omitted.

La realtà è più complessa e cambia in funzione del tipo di esecuzione (locale o Web) e del sistema operativo. Non ne parlo in questa serie di post introduttivi.

When a string that does not look like a relative or absolute path is given to require, it is assumed to refer to either a built-in module or a module installed in a node_modules directory. For example, require("fs") will give you Node’s built-in file system module, and require("elife") will try to load the library found in node_modules/elife/. A common way to install such libraries is by using NPM, which I will discuss in a moment. OOPS! ci dice (quasi tutto) Marijn 🚀

To illustrate the use of require, let’s set up a simple project consisting of two files. The first one is called main.js, which defines a script that can be called from the command line to garble a string.

var garble = require("./garble");

// Index 2 holds the first actual command-line argument
var argument = process.argv[2];

console.log(garble(argument));

The file garble.js defines a library for garbling strings, which can be used both by the command-line tool defined earlier and by other scripts that need direct access to a garbling function.

module.exports = function(string) {
  return string.split("").map(function(ch) {
    return String.fromCharCode(ch.charCodeAt(0) + 5);
  }).join("");
};

Remember that replacing module.exports, rather than adding properties to it, allows us to export a specific value from a module. In this case, we make the result of requiring our garble file the garbling function itself.

The function splits the string it is given into single characters by splitting on the empty string and then replaces each character with the character whose code is five points higher. Finally, it joins the result back into a string.

We can now call our tool like this:

Installare con NPM
NPM, which was briefly discussed in Chapter 10 [qui], is an online repository of JavaScript modules, many of which are specifically written for Node. When you install Node on your computer, you also get a program called npm, which provides a convenient interface to this repository.

For example, one module you will find on NPM is figlet, which can convert text into ASCII art—drawings made out of text characters. The following transcript shows how to install and use it:

OK, qualche warning e svela che uso una directory particolare (non conto di usare JavaScript oltre questi posts).

After running npm install, NPM will have created a directory called node_modules. Inside that directory will be a figlet directory, which contains the library. When we run node and call require("figlet"), this library is loaded, and we can call its text method to draw some big letters.

Somewhat unexpectedly perhaps, instead of simply returning the string that makes up the big letters, figlet.text takes a callback function that it passes its result to. It also passes the callback another argument, error, which will hold an error object when something goes wrong or null when everything is all right.

This is a common pattern in Node code. Rendering something with figlet requires the library to read a file that contains the letter shapes. Reading that file from disk is an asynchronous operation in Node, so figlet.text can’t immediately return its result. Asynchronicity is infectious, in a way—every function that calls an asynchronous function must itself become asynchronous.

There is much more to NPM than npm install. It reads package.json files, which contain JSON-encoded information about a program or library, such as which other libraries it depends on. Doing npm install in a directory that contains such a file will automatically install all dependencies, as well as their dependencies. The npm tool is also used to publish libraries to NPM’s online repository of packages so that other people can find, download, and use them.

This book won’t delve further into the details of NPM usage. Refer to npmjs.org for further documentation and for an easy way to search for libraries.

:mrgreen:

JavaScript 79 – Node.js – 1

Continuo da qui, copio qui.

So far, you have learned the JavaScript language and used it within a single environment: the browser. [Ma adesso we] will briefly introduce you to Node.js, a program that allows you to apply your JavaScript skills outside of the browser. With it, you can build anything from simple command-line tools to dynamic HTTP servers.

These chapters aim to teach you the important ideas that Node.js builds on and to give you enough information to write some useful programs for it. They do not try to be a complete, or even a thorough, treatment of Node.

Whereas you could run the code in previous chapters directly on these pages, since it was either raw JavaScript or written for the browser, the code samples in this chapter are written for Node and won’t run in the browser.

If you want to follow along and run the code in this chapter, start by going to nodejs.org and following the installation instructions for your operating system. Also refer to that website for further documentation about Node and its built-in modules.

Background
One of the more difficult problems with writing systems that communicate over the network is managing input and output—that is, the reading and writing of data to and from the network, the hard drive, and other such devices. Moving data around takes time, and scheduling it cleverly can make a big difference in how quickly a system responds to the user or to network requests.

The traditional way to handle input and output is to have a function, such as readFile, start reading a file and return only when the file has been fully read. This is called synchronous I/O (I/O stands for input/output).

Node was initially conceived for the purpose of making asynchronous I/O easy and convenient. We have seen asynchronous interfaces before, such as a browser’s XMLHttpRequest object. An asynchronous interface allows the script to continue running while it does its work and calls a callback function when it’s done. This is the way Node does all its I/O.

JavaScript lends itself well to a system like Node. It is one of the few programming languages that does not have a built-in way to do I/O. Thus, JavaScript could be fit onto Node’s rather eccentric approach to I/O without ending up with two inconsistent interfaces. In 2009, when Node was being designed, people were already doing callback-based I/O in the browser, so the community around the language was used to an asynchronous programming style.

Asincronicità
Qui Marijn spiega in dettaglio (forse anche troppo approfonditamente) le differenti impostazioni di due categorie complementari di programmi, cosa che vi farà dire “ah!” perché scoprirete di sapere (almeno in parte).

I’ll try to illustrate synchronous versus asynchronous I/O with a small example, where a program needs to fetch two resources from the Internet and then do some simple processing with the result.

In a synchronous environment, the obvious way to perform this task is to make the requests one after the other. This method has the drawback that the second request will be started only when the first has finished. The total time taken will be at least the sum of the two response times. This is not an effective use of the machine, which will be mostly idle when it is transmitting and receiving data over the network.

The solution to this problem, in a synchronous system, is to start additional threads of control [qui]. A second thread could start the second request, and then both threads wait for their results to come back, after which they resynchronize to combine their results.

In the following diagram, the thick lines represent time the program spends running normally, and the thin lines represent time spent waiting for I/O. In the synchronous model, the time taken by I/O is part of the timeline for a given thread of control. In the asynchronous model, starting an I/O action conceptually causes a split in the timeline. The thread that initiated the I/O continues running, and the I/O itself is done alongside it, finally calling a callback function when it is finished.

Another way to express this difference is that waiting for I/O to finish is implicit in the synchronous model, while it is explicit, directly under our control, in the asynchronous one. But asynchronicity cuts both ways. It makes expressing programs that do not fit the straight-line model of control easier, but it also makes expressing programs that do follow a straight line more awkward.

In Chapter 17, I already touched on the fact that all those callbacks add quite a lot of noise and indirection to a program. Whether this style of asynchronicity is a good idea in general can be debated. In any case, it takes some getting used to.

But for a JavaScript-based system, I would argue that callback-style asynchronicity is a sensible choice. One of the strengths of JavaScript is its simplicity, and trying to add multiple threads of control to it would add a lot of complexity. Though callbacks don’t tend to lead to simple code, as a concept, they’re pleasantly simple yet powerful enough to write high-performance web servers.

La modalità Comando
When Node.js is installed on a system, it provides a program called node, which is used to run JavaScript files. Say you have a file hello.js, containing this code:

var message = "Hello world!";
console.log(message);

You can then run node from the command line like this to execute the program:

The console.log method in Node does something similar to what it does in the browser. It prints out a piece of text. But in Node, the text will go to the process’ standard output stream, rather than to a browser’s JavaScript console.

If you run node without giving it a file, it provides you with a prompt at which you can type JavaScript code and immediately see the result.

Al posto di process.exit(0) se uso Linux posso usare Ctrl-D, per Windows (credo) invece Ctrl-Z.

The process variable, just like the console variable, is available globally in Node. It provides various ways to inspect and manipulate the current program. The exit method ends the process and can be given an exit status code, which tells the program that started node (in this case, the command-line shell) whether the program completed successfully (code zero) or encountered an error (any other code).

To find the command-line arguments given to your script, you can read process.argv, which is an array of strings. Note that it also includes the name of the node command and your script name, so the actual arguments start at index 2.
Ecco showargv.js

console.log(process.argv);

you could run it like this:

All the standard JavaScript global variables, such as Array, Math, and JSON, are also present in Node’s environment. Browser-related functionality, such as document and alert, is absent.

The global scope object, which is called window in the browser, has the more sensible name global in Node.

Pausa ma prima una cosa in sospeso, da qui:

if (process.argv.length > 2) {
  var F = process.argv[2];
  
  var C = (F - 32) * 5 / 9;
  C = C.toFixed(0);  
  console.log(F, "°F ->", C, "°C"); 
}

:mrgreen:

JavaScript 78 – Tutto sulla programmazione nel browser – 2

Continuo da qui.

The dream behind the Web is of a common information space in which we communicate by sharing information. Its universality is essential: the fact that a hypertext link can point to anything, be it personal, local or global, be it draft or highly polished.
Tim Berners-Lee.

Ottima cit. per iniziare il capitolo su HTTP 😊
Poi Marijn spiega bene il protocollo HTTP, i messaggi che intercorrono tra te e il server e poi si arriva al browser con le URLs. Seguono XML, le request con sandox e le pomises. Infine un accenno alla sicurezza, argomento che andrebbe ampliato. Ma per intanto HTTPS.
Insomma un capitolo tutto da leggere e roba di tutti i giorni per tanti programmatori 😎

Intanto io passo al prossimo capitolo, le forms (le finestre di dialogo), per esempio


Le forms hanno diversi tipi di campi che vengono esaminati in dettaglio, per esempio

Ci sarebbero gli esercizi (Life di Conway) ma passo al prossimo capitolo, è un esercizio: A Paint Program per fare cose come questa:


Tanto JavaScript, da inserire in una pagina HTML. Per intanto pausa, poi si passerà a Node.js 😎

:mrgreen:

JavaScript 77 – Tutto sulla programmazione nel browser – 1

Continuo da qui.

Il progetto di un gioco nel browser
My initial fascination with computers, like that of many kids, originated with computer games. I was drawn into the tiny computer-simulated worlds that I could manipulate and in which stories (sort of) unfolded—more, I suppose, because of the way I could project my imagination into them than because of the possibilities they actually offered.

Comincia così il prossimo capitolo di Marijn 🚀 e continua dicendo:

This chapter will walk through the implementation of a simple platform game. Platform games (or “jump and run” games) are games that expect the player to move a figure through a world, which is often two-dimensional and viewed from the side, and do lots of jumping onto and over things.

E il gioco lo fa tutto e rockz 🚀 tutto da giocarci 😊 e studiarlo se si vuole approfondire JavaScript e diventare very über nerd 😊

Siccome è troppo specifico non lo copio, vedetelo di là.

Anche il capitolo successivo, disegnare sul canvas è specialistico; siccome riguarda solo il browser lo vedete di là, vero? 😎

Ebbene sì, sono giunto a qualcosa fuori dal mio mondo, anche se non si è interessati a programmare per il browser sono cose da leggere, perché si usano continuamente. E ormai i nuovi sono tutti sul Web (OK, quasi). Pausa, devo leggere anch’io 😯

:mrgreen:

JavaScript 76 – gestione degli eventi (nel browser)

Continuo da qui, copio qui.

Some programs work with direct user input, such as mouse and keyboard interaction. The timing and order of such input can’t be predicted in advance. This requires a different approach to control flow than the one we have used so far.

, quasi tutti i programmi funzionano così. Fanno eccezione i comandi da terminale e pochi altri. Qui, seguendo Marijn, qualche cenno, sempre relativo al browser.

Gestori di eventi
Imagine an interface where the only way to find out whether a key on the keyboard is being pressed is to read the current state of that key. To be able to react to keypresses, you would have to constantly read the key’s state so that you’d catch it before it’s released again. It would be dangerous to perform other time-intensive computations since you might miss a keypress.

That is how such input was handled on primitive machines. A step up would be for the hardware or operating system to notice the keypress and put it in a queue. A program can then periodically check the queue for new events and react to what it finds there.

Of course, it has to remember to look at the queue, and to do it often, because any time between the key being pressed and the program noticing the event will cause the software to feel unresponsive. This approach is called polling. Most programmers avoid it whenever possible.

A better mechanism is for the underlying system to give our code a chance to react to events as they occur. Browsers do this by allowing us to register functions as handlers for specific events.

The addEventListener function registers its second argument to be called whenever the event described by its first argument occurs.

Segue una lunga lezione, esaustiva, che non riporto. Al solito –mi ripeto– sto solo vedendo il linguaggio JavaScript per apprenderne le basi. Riporto solo le conclusioni di Marijn 🚀

Event handlers make it possible to detect and react to events we have no direct control over. The addEventListener method is used to register such a handler.

Each event has a type ("keydown", "focus", and so on) that identifies it. Most events are called on a specific DOM element and then propagate to that element’s ancestors, allowing handlers associated with those elements to handle them.

When an event handler is called, it is passed an event object with additional information about the event. This object also has methods that allow us to stop further propagation (stopPropagation) and prevent the browser’s default handling of the event (preventDefault).

Pressing a key fires "keydown", "keypress", and "keyup" events. Pressing a mouse button fires "mousedown", "mouseup", and "click" events. Moving the mouse fires “mousemove” and possibly "mouseenter" and "mouseout" events.

Scrolling can be detected with the "scroll" event, and focus changes can be detected with the "focus" and "blur" events. When the document finishes loading, a “load” event fires on the window.

Only one piece of JavaScript program can run at a time. Thus, event handlers and other scheduled scripts have to wait until other scripts finish before they get their turn.

:mrgreen:

JavaScript 75 – DOM – Document Object Model

Continuo da qui, copio qui.

When you open a web page in your browser, the browser retrieves the page’s HTML text and parses it. The browser builds up a model of the document’s structure and then uses this model to draw the page on the screen.

This representation of the document is one of the toys that a JavaScript program has available in its sandbox. You can read from the model and also change it. It acts as a live data structure: when it is modified, the page on the screen is updated to reflect the changes.

E di qui Marijn parte a raccontarci tutto (davvero tutto) sulla pagina HTML. Ottimo, da leggere ma non pertinente con questa serie (introduttiva) di JavaScirpt.

Per cui salto dopo riportando solo il

Riepilogo
JavaScript programs may inspect and interfere with the current document that a browser is displaying through a data structure called the DOM. This data structure represents the browser’s model of the document, and a JavaScript program can modify it to change the visible document.

The DOM is organized like a tree, in which elements are arranged hierarchically according to the structure of the document. The objects representing elements have properties such as parentNode and childNodes, which can be used to navigate through this tree.

The way a document is displayed can be influenced by styling, both by attaching styles to nodes directly and by defining rules that match certain nodes. There are many different style properties, such as color or display. JavaScript can manipulate an element’s style directly through its style property.

:mrgreen:

JavaScript 74 – il browser

Continuo da qui, copio qui.

The browser is a really hostile programming environment.
Douglas Crockford.

The next part of this book will talk about web browsers. Without web browsers, there would be no JavaScript. And even if there were, no one would ever have paid any attention to it.

Vero. Ma vero anche che a me interessa poco la visualizzazione nel browser, questa serie di posts sono introduttivi a JavaScript come linguaggio. Quindi riassumerò il post di Marijn.

Di là trovate una breve sintesi sulle reti, Internet, il TCP, il Web e infine il protocollo HTML.

Dentro il codice HTML ci possono essere script JavaScript, per esempio:

che eseguito nel browser produce:

Such a script will run as soon as its <script> tag is encountered as the browser reads the HTML.

Including large programs directly in HTML documents is often impractical. The <script> tag can be given an src attribute in order to fetch a script file (a text file containing a JavaScript program) from a URL.


The code/hello.js file included here contains the same simple program, alert("hello!"). When an HTML page references other URLs as part of itself, for example an image file or a script—web browsers will retrieve them immediately and include them in the page.

:mrgreen: