These are some unstructured notes on my current understanding of Node.js

What is Node.js ?

Node.js is a Free and opensource Javascript runtime, asynchronous in nature, on a single thread. It wraps the V8 engine used in chrome, to compile to machine code. The wrapper adds serverside features, such as IO, DB interaction, content serving and loses navigator-specific functionalities such as DOM interactions.

Some notable differences between Node.js and its frontend counterparts

  • On the frontend, there is a window global object, it is called global in Node.js and differs in the methods and attributes proposed: setInterval, setTimeout, clearInterval, __dirname, __filename
  • Node uses the CommonJS syntax to import modules: const xyz = require('./path_to_module');
    • explicit exports are required (modules.exports = <...> for example, but there are other ways)
    • In Browser JS and since ES6, imports use the import X from 'package' syntax

Some notable features

  • Node.js Event Loop
    • Continuously checks the call stack
    • process.nextTick(() => {...}): tell the JS engine to run the function code after the current operation is done but before anything else (e.g. at the end of the current tick). Several calls to nextTick are run in order.
    • setTimeout(() => {}, 0) will run the function at the end of the next tick
    • Queues of the event loop listed by priority:
      • nextTick queue
      • microtasks queue (promises, Promise.then())
      • macrotasks queue (setTimeout, setImmediate)
      • More: https://nodejs.dev/en/learn
  • Promises:
    • A solution to Callback Hell
    • Runs asynchronously, in Pending state
    • Either end in a Resolved state (triggers then) or a Rejected state (triggers catch)
      const isItDoneYet = new Promise((resolve, reject) => {
      if (done) {
          const workDone = 'Here is the thing I built';
          resolve(workDone);
      } else {
          const why = 'Still working on something else';
          reject(why);
      }
      });
      
  • Event Emitter: event management
      myEvent.on("test-event", (data) => {...})
      [...]
      myEvent.emit("test-event", { name: "yoann" })
    

Notable mentions

  • The package manager is NPM
    • package.json file: package information (what does it mean to run the package, what are the dependencies…) npm init creates a base for the package.json file
    • npm install x add the requirement in the package.json file
  • Express: Goto http framework/router for a node API.

References

  • https://www.youtube.com/watch?v=hKyudh3rC_A
  • https://nodejs.dev/en/learn
  • http://callbackhell.com/