Node.js

IDE:

REPL

  • access last expression, use _
  • save session with .save filename, clear to clear and load to load
  • after v0.8, type built-in module name, such as fs, loads the module

Core

Global Objects

global
global is global namespace object, similar to windows in a browser environment. To print out global object, under REPL:

console.log(global);

process

  • stdin and stdout are asynchronous. stderr is synchronous, blocking stream.
  • reading stdin and writing to stdout
    process.stdin.resume();
    process.stdin.on('data', function(chunk){
        process.stdout.write(chunk);
    });
  • process.memoryUsage tells us how much memory the Node application is using.
  • use process.nextTick if you wanted to delay a function. (process.nextTick was called far more quickly than setTimeout with a zero-millisecond delay).to ensure callback is truly asynchronous:
    setTimeout(function() {
        callback(val);
    }, 0);
    // more efficient
    function asynchFunction = function (data, callback) {
        process.nextTick(function() {
            callback(val);
        });
     );

buffer
buffer handles binary data in Node.

  • convert binary data to string, use setEncoding
  • write string to buffer
    buf.write(string); // offset defaults to 0, length defaults to buffer.length - offset, encoding is utf8

TCP Sockets and Servers

A socket is an endpoint in a communication. The data flows between the sockets in what’s known as a stream. The data in the stream can be transmitted as binary data in a buffer, or in Unicode as a string.

Search Blog: