Nodejs

GitbookBackend2021-02-10


🪕 Node


Node.js = Runtime Environment + JavaScript Library

  • Asynchronous and Event Driven
  • Very Fast
  • Single Threaded but Highly Scalable
  • No Buffering
  • MIT License

nodejs concepts

🪕 Event Loop


Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute.

Event-Driven

// Import events module
var events = require("events");

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Bind event and event  handler as follows
eventEmitter.on("eventName", eventHandler);

// Fire an event
eventEmitter.emit("eventName");

🪕 Event Emitter


// Import events module
var events = require("events");

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
  • addListener(event, listener)
  • on(event, listener)
  • once(event, listener)
  • removeListener(event, listener)
  • removeAllListeners([event])
  • setMaxListeners(n)
  • listeners(event)
  • emit(event, [arg1], [arg2], [...])

    const EventEmitter = require("events");
    
    class MyEmitter extends EventEmitter {}
    
    const myEmitter = new MyEmitter();
    myEmitter.on("event", () => {
    	console.log("an event occurred!");
    });
    myEmitter.emit("event");

🪕 Buffers


  • binary data (TCP stream, file system)
  • Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.
  • Buffer class is a global class that can be accessed in an application without importing the buffer module.
var buf = new Buffer(10);

🪕 Streams


  • Readable − Stream which is used for read operation.
  • Writable − Stream which is used for write operation.
  • Duplex − Stream which can be used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on input.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are −

  • data − This event is fired when there is data is available to read.
  • end − This event is fired when there is no more data to read.
  • error − This event is fired when there is any error receiving or writing data.
  • finish − This event is fired when all the data has been flushed to underlying system.
  • pipe, chain
var fs = require("fs");
var data = "";

// Create a readable stream
var readerStream = fs.createReadStream("input.txt");

// Set the encoding to be utf8.
readerStream.setEncoding("UTF8");

// Handle stream events --> data, end, and error
readerStream.on("data", function (chunk) {
	data += chunk;
});

readerStream.on("end", function () {
	console.log(data);
});

readerStream.on("error", function (err) {
	console.log(err.stack);
});

console.log("Program Ended");

🪕 File System


  • open
  • stat
  • writeFile
  • read, readFile, readFileSync
  • close
  • unlink
  • mkdir
  • readdir

🪕 Global Objects


  • process
  • __filenmae
  • __dirname
  • setTimeout/clearTimeout
  • setInterval/clearInterval
  • console

🪕 Utility Modules


  • os
  • path
  • net
  • dns
  • domain

🪕 Web Module


web architecture

🪕 RESTful API


🪕 Scaling Application


  • exec: child_process.exec(command[, options], callback)
  • spawn: child_process.spawn(command[, args][, options])
  • fork: child_process.fork(modulePath[, args][, options])
const fs = require("fs");
const child_process = require("child_process");

for (var i = 0; i < 3; i++) {
	var worker_process = child_process.fork("support.js", [i]);

	worker_process.on("close", function (code) {
		console.log("child process exited with code " + code);
	});
}

🪕 Packaging


🪕 read json file


//1
const data = require("path/json");
//2
const fs = require("fs");
fs.readFile("user.json", (err, data) => {
	if (err) throw err;
	const users = JSON.parase(data);
	console.log(users);
});

🪕 Q/A


  • Differentiate between readFile vs createReadStream in Node.js?

    • readFile: fully buffered process
    • createReadStream: partially buffered
  • setImmediate/clearImmediate – Used to execute code at the end of the current event loop cycle
  • process.nextTick – Used to schedule a callback function that needs to be invoked in the next iteration of the Event Loop
  • exit codes

    • Uncaught fatal exception
    • Unused
    • Fatal Error
    • Internal Exception handler Run-time failure
    • Internal JavaScript Evaluation Failure

node fullstack