# Basics

[Event demultiplexing](https://jsblog.insiderattack.net/event-loop-and-the-big-picture-nodejs-event-loop-part-1-1cb67a182810) is used to avoid waiting for I/O events and is design principle behind [Reactor pattern](https://hackernoon.com/the-node-js-system-51090c35dddc), which is the main principle in NodeJS - [event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/).

## 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);
    })
  }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ondrej-kvasnovsky-2.gitbook.io/nodejs-handbook/basics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
