Archivi Categorie: JavaScript

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);
    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 for specifics (dir.js).

var fs = require("fs");

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

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ù 😜


JavaScript 80 – Node.js – 2

Continuo da qui, copio qui.

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];


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);

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 for further documentation and for an easy way to search for libraries.


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 and following the installation instructions for your operating system. Also refer to that website for further documentation about Node and its built-in modules.

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.

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!";

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


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"); 


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 😎


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 😯


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.


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

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.


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.


JavaScript 73 – progetto di un linguaggio di programmazione – 8

Continuo da qui, copio qui.

Aggiustare lo scope
Scope si potrebbe tradurre vita o visibilità o chissà come; io sono di una ‘gnuransa encyclopedica, si sa 😡

Currently, the only way to assign a variable a value is define. This construct acts as a way both to define new variables and to give existing ones a new value.

This ambiguity causes a problem. When you try to give a nonlocal variable a new value, you will end up defining a local one with the same name instead. (Some languages work like this by design, but I’ve always found it a silly way to handle scope.)

Add a special form set, similar to define, which gives a variable a new value, updating the variable in an outer scope if it doesn’t already exist in the inner scope. If the variable is not defined at all, throw a ReferenceError (which is another standard error type).

The technique of representing scopes as simple objects, which has made things convenient so far, will get in your way a little at this point. You might want to use the Object.getPrototypeOf function, which returns the prototype of an object. Also remember that scopes do not derive from Object.prototype, so if you want to call hasOwnProperty on them, you have to use this clumsy expression:, name);

This fetches the hasOwnProperty method from the Object prototype and then calls it on a scope object.

Non ci sono riuscito (forse non mi sono applicato abbastanza); ho copiato qui
aggiungendo al file p-egg.js dei post precedenti il seguente codice:

specialForms["set"] = function(args, env) {
  if (args.length != 2 || args[0].type != "word")
    throw new SyntaxError("Bad use of set");
  var varName = args[0].name;
  var value = evaluate(args[1], env);

  for (var scope = env; scope; scope = Object.getPrototypeOf(scope)) {
    if (, varName)) {
      scope[varName] = value;
      return value;
  throw new ReferenceError("Setting undefined variable " + varName);

dopo l’ultima specialForms.
Ho poi creato il file scope.js:

require("./load.js") ("/p-egg.js");

run("do(define(x, 4),",
    "   define(setx, fun(val, set(x, val))),",
    "   setx(50),",
    "   print(x))");

run("set(quux, true)");

Eseguendolo però non ottengo quanto previsto, ecco il mio risultato

e quello atteso, di Marijn:


JavaScript 72 – progetto di un linguaggio di programmazione – 7

Continuo da qui, copio qui.
Sempre esercizi.

Commenti in Egg
It would be nice if we could write comments in Egg. For example, whenever we find a hash sign (#), we could treat the rest of the line as a comment and ignore it, similar to // in JavaScript.

We do not have to make any big changes to the parser to support this. We can simply change skipSpace to skip comments like they are whitespace so that all the points where skipSpace is called will now also skip comments. Make this change.

L’esercizio ha due aspetti: nodificare la regexp inserendo # e modificare il codice del linguaggio (p-egg.js) per cambiare la funzione skipSpace. Ma non ci sono riuscito. E non ho capito dove sbaglio, non ho trovato delucidazioni né su Stack Overflow né su Google. Sicuramente un errore mio ma non so quale.

La soluzione di Marijn, qui:

function skipSpace(string) {
  var skippable = string.match(/^(\s|#.*)*/);
  return string.slice(skippable[0].length);

console.log(parse("# hello\nx"));

console.log(parse("a # one\n   # two\n()"));