NodeJS Handbook
  • Introduction
  • Basics
  • Experiments
    • Dependency Injection and AOP
  • Performance Testing
  • Running Servers
  • Node Version Manager
  • Koa
  • PM2
  • GraphQL
Powered by GitBook
On this page

Was this helpful?

Basics

Event demultiplexing is used to avoid waiting for I/O events and is design principle behind Reactor pattern, which is the main principle in NodeJS - event loop.

Asynchronous and synchronous operations

We should avoid synchronous functions in the code because they block the event loop. We also shouldn't mix synchronous and asynchronous code in single function.

const fs = require('fs');
const cache = {};
const inconsistentRead = function(fileName, callback) {
  if (cache[fileName]) {
    // invoked synchronously
    // callback(cache[fileName]);
    // make it asynchronous - and puts it before any IO event in the event loop
    process.nextTick(() => callback(cache[fileName]));
    // or make it asynchronous - and puts it at after all the IO events in the event loop
    setImmediate(() => callback(cache[fileName]));
  } else {
    // invoked asynchronously
    fs.readFile(fileName, 'utf8', (err, data) => {
      cache[fileName] = data;
      callback(data);
    })
  }
};
PreviousIntroductionNextExperiments

Last updated 5 years ago

Was this helpful?