Node.js study note

Survey:

Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications. Node.js is not a JavaScript framework,[3] but its applications are written in JavaScript and can be run within the Node.js runtime on a wide variety of platforms.

This is my first time to learn Node.js, and I’ll write casully about the process and experience of learning.


Content:

–1– Argument variables with process.argv

app.js

function grab(flag){
    var index = process.argv.indexOf(flag);
    return (index === -1) ? null : process.argv[index+1];
}

var greeting = grab('--greeting');
var user = grab('--user');

if (!user || !greeting) {
    console.log("You blew it!");
} else {
    console.log(`Welcome, ${user}, ${greeting}`);
}

In this code, we grab the arguments from shell and print it out on the console.

For example, if in the shell:

$node app --user Martin --greeting "hello hello"

Then in the console:

Welcome, Martin, hello hello

And in this code, I also learned string temple which uses backticks.Welcome, ${user}, ${greeting}` will contain variable user and greeting.


–2– Standard input and standard output

 var questions = [
"What is your name?",
"What is your favorite hobby?",
"What is your preferred programming language?"
];

var answers = [];

function ask(i) {
    process.stdout.write(`\n\n\n\n ${questions[i]}`);
    process.stdout.write("  >  ");
}

process.stdin.on('data', function(data){

    answers.push(data.toString().trim());

    if (answers.length < questions.length) {
        ask(answers.length);
    } else {
        process.exit();
    }
});

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

    process.stdout.write("\n\n\n\n");

    process.stdout.write(`Go ${answers[1]} ${answers[0]} you can finish writing ${answers[2]} later`);

    process.stdout.write("\n\n\n\n");

});

ask(0);

In the shell:

What is your name?  >  Martin




 What is your favorite hobby?  >  play games




 What is your preferred programming language?  >  python




Go play games Martin you can finish writing python later

Is that funny:)?


–3– Global timing functions

There are several functions about the timing such as setInterval, setTimeout and clearInterval. It’s useful while developing web interactive program.

Code:

var waitTime = 3000;
var currentTime = 0;
var waitInterval = 10;
var percentWaited = 0;

function writeWaitingPercent(p){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    process.stdout.write(`waiting ... ${p}%`);

}


var interval = setInterval(function(){
    currentTime += waitInterval;
    percentWaited = Math.floor((currentTime/    waitTime)*100);
    //console.log(`waiting ${currentTime/1000} seconds`);
    writeWaitingPercent(percentWaited);
}, waitInterval);

setTimeout(function(){

    clearInterval(interval);
    console.log("\ndone");
}, waitTime);

process.stdout.write("\n\n");
writeWaitingPercent(percentWaited);

In the shell:

waiting ... 81%
done

–4– Core modules:

Node.js use require function to get modules. This section is going to show some modules of Node.js.

Code:

var path = require('path');
var util = require('util');
var v8 = require('v8')


util.log( path.basename(__filename) );

var dirUploads = path.join(__dirname, 'www', 'fileds', 'uploads');

util.log(dirUploads);

util.log(v8.getHeapStatistics());

In the shell:

node core
28 Jan 23:34:37 - core.js
28 Jan 23:34:37 - /Users/Martin/Documents/martin/    Study/Node/www/fileds/uploads
28 Jan 23:34:37 - { total_heap_size: 7523616,
  total_heap_size_executable: 5242880,
  total_physical_size: 7523616,
  total_available_size: 1491271696,
  used_heap_size: 4094992,
  heap_size_limit: 1535115264 }

–5– Collecting information with Readline

Realine is a module of Node.js, it should get the input stream and output stream. Then you can use the API to operate the input and output such as setPrompt, prompt, on and etc. A string in the string can be replaced as s% like in the C, and the JSON string will be replaced as j%.

Code:

var readline = require('readline');

var rl = readline.createInterface(process.stdin, process.stdout);

var realPerson = {
    name: '',
    sayings: []
};

rl.question("What is the name of a real person?", function(answer){

    realPerson.name = answer;

    rl.setPrompt(`What would ${realPerson.name} say? `);

    rl.prompt();

    rl.on('line', function(sayings){

        realPerson.sayings.push(sayings.trim());

        if (sayings.toLowerCase().trim() == 'exit'){
            rl.close();
        }
        else{
        rl.setPrompt(`What else would ${realPerson.name} say? ('exit' to leave)`);
        rl.prompt();
        }
    });

});

rl.on('close', function(){
     console.log("%s is a real person that says j%",     realPerson.name, realPerson.sayings);
})

In the shell:

What is the name of a real person?Martin
What would Martin say? haha
What else would Martin say? ('exit' to leave)heihei
What else would Martin say? ('exit' to leave)exit
Martin is a real person that says j% [ 'haha', 'heihei', 'exit' ]

–6– Handling events with EventEmitter

There are two modules I have learned from this class. One is event and the other is util. Event has two functions which called on and emit. The fucntion on is for naming the event, and the function emit is for triggling the event. The module util is for inheriting from other class.

Code:

var events = require('events');

var emitter = new events.EventEmitter();

emitter.on('customEvent', function(message, status){

    console.log(`${status}: ${message}`);

});

emitter.emit('customEvent', "Hellow World", 200);

And

node BenFranklin.js 
Ben Franklin: You may delay, but time will not.

–7–Exporting custom modules

In this class, I learned that in one js file, we can conclude a export sentence to export a file to become a module. For example, “module.exports = Person;”

Code:

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var Person = function(name) {
    this.name = name;
};

util.inherits(Person, EventEmitter);

module.exports = Person;

–8–Creating child process with exec

In this class, I learned the module called child_process. And it has a function called exec which is aiming at execute the command in the command line.

Code:

var exec = require("child_process").exec;

exec("ls", function(err, stdout){

    if (err){
        throw err;
    }

    console.log("Listing Finished");

    console.log(stdout);

});

–9–Creating child process with spawn

Spawn can deal with the situation that you want run serval commands or deal with the stdout and stdin.

Code:

var spawn = require("child_process").spawn;

var cp = spawn("node", ["alwaysTalking"]);

cp.stdout.on("data", function(data){
    console.log(`STDOUT: ${data.toString()}`);
});

cp.on("close", function() {

    console.log("Child Process has ended");

    process.exit();

});

setTimeout(function () {

    cp.stdin.write("stop");

}, 4000);

–10–Listing directory files

What’s the differences between synchronously and asynchronously:

When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.

That being, said, in the context of computers this translates into executing a process or task on another “thread.” A thread is a series of commands–a block of code–that exists as a unit of work. The operating system can manage multiple threads and assign a thread a piece (“slice”) of processor time before switching to another thread to give it a turn to do some work. At its core (pardon the pun), a processor can simply execute a command–it has no concept of doing two things at one time. The operating system simulates this by allocating slices of time to different threads.

Now, if you introduce multiple cores/processors into the mix, then things CAN actually happen at the same time. The operating system can allocate time to one thread on the first processor, then allocate the same block of time to another thread on a different processor.

All of this is about allowing the operating system to manage the completion of your task while you can go on in your code and do other things.

Reference: http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean

In this section, I learned read files synchronously or asynchronously.

Code:

var fs = require("fs");

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

console.log("Reading Files...");

–11–Reading files

Code:

var fs = require("fs");

fs.readFile("./lib/saying.md", "UTF-8", function(err, contents){

    if (err) {
        throw err;
    }

    console.log(contents);
});