<tech> brunch ;


Node.js Quick Reference Guide

  • Node.js is not a programming language. It’s not even a framework. It’s a runtime environment, written in C++,
    which uses Google Chrome’s V8 engine. It was devised to run JavaScript outside of Web Browsers on backend servers.
    Web browsers have JavaScript engines, which allow execution of JavaScript codes inside them.
    Internet Explorer has Chakra, Mozilla has SpiderMonkey and Google Chrome has V8 engine for JavaScript execution in these browsers.

  • Node.js uses single thread. That single thread serves different i/o requests. While processing for one i/o request is going on, our single thread can go and serve other i/o request.
    Node server can be used for Data/I/O related purposes. But not in scenarios where we need to have bigger computational power of CPU.
    By default, Node is asynchronous. But it can works both ways - synchronous as well as asynchronous.


    Flow Diagram

  • When executing inside web browsers, JavaScript has ‘window’ as the global variable defined.
    This window variable can be used to refer to other components defines within the JavaScript code.
    While executing JavaScript inside Node, we have ‘global’ as the global variable, which can be used to refer to
    components defined within the JavaScript code. As always, dropping the global/window variable is a shorthand and that’s which is widely used by developers.

  • Exporting and Loading of modules in Node.
    We use module.exports for exposing the components to be used by other js files in Node.
    We use require(), in order to import the exported modules.
    In modules, we can exports a single function or an object.
    ‘module’ is one such variable which cannot be accessed by ‘global’ variable inside node.

  • Node has some inbuilt modules like fs(FileStream), http etc. which serves our purpose to a great extent and allows us to use them, without having to worry about writing the logic on our own.

  • Module Wrapper Function: Node doesn’t execute our code directly. Each file with snippets of code directly. It wraps everything inside of a function, which has parameters-exports, require, module, filename, dirname.
    Inside this function, our code executes. This function is called Module Wrapper Function. So by looking at the arguments, we can say that ‘require’ seems to be global, but its not. It is local to a Module Wrapper Function.
    filename is the variable which refers to the current filename’s fully qualified path. dirname is the fully qualified path to the current file’s directory.

  • Some frequently used inbuilt Node modules are : path(for path related activities), os(for operating system related utility methods), fs(for FileStream related activities), events( to signal that something has happened in our application), http(for http related activities).

  • Events module, and the EventEmitter class has a very high importance because of the potential that these give to developers:

    1
    2
    3
    4
    5
    cont EventEmitter = require('events');
    // EventEmitter is a class.
    // we need to create instance of this class in order to use its methods.
    const emitter = new EventEmitter();
    emitter.emit("message", {id:1, url:'http://anshulgautam.in'}); // signalling that an event has happened.

.addListener and on (they both serve the same purpose).

1
2
3
4
5
// Registering the Listener.
emitter.on("message", function(arg) {
console.log("Listener called");
console.log(arg.url);
});

Listeners go synchronously to find which signal has been received first.

From ECMA Script 6 onwards, function() {} is synonymous to () => {}.

In case we can to extend EventEmitter class:

1
2
3
4
5
6
7
8
class Logger extends EventEmitter {
log(arg) {
console.log(arg);
this.emit("message", {id:1, url:'http://anshulgautam.in'});
}
}

module.exports = Logger;

For using this exported class:

1
2
3
const Logger = require('./logger');
const log = new Logger();
log.log("hi");

  • Another frequently used node module is HTTP.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const http = require('http');
const server = http.createServer(); // this server has all the capabilities of EventEmitter.
server.on('connection', (socket) => {
console.log('New Connection established.');
});
server.listen(3000);
console.log('Listening on port 3000...');

Another, and a simple way to create the server:
const server = http.createServer((req, res) => {
if(req.url === '/') {
res.write('Hello World!');
res.end();
}
});

Nowadays, to handle various routes, we use a framework called Express, which handles such routes easily and in a cleaner way. Express is built on top of HTTP module in Node.
That will be part of another post on this site. =)