This is the third day of my participation in Gwen Challenge

Starting today, I plan to embark on a journey of learning about Node, by understanding the language capabilities of JS, going beyond the browser to do things on the computer system layer, and waving the invisible wings of JS.

The basic concept

First, what is NodeJS? To the official website definition:

  • Chrome V8 based JS runtime environment
  • Use event loops, non-blocking I/O model

(I know all these words, but I can’t read them together.)

Event loop

The NodeJS main thread is responsible for event scheduling and continuously drives event execution. Outside of the main thread, there is a task queue. The main thread puts the tasks that need to be executed or calculated into the queue, and the sub-process executes them. When the processing is complete, the main thread retrieves the results from the task queue.

NodeJS is often said to be single-threaded, which means that its main thread is single-threaded, but it does not mean that it is inefficient.

Non-blocking I/O

I/O (input/ Output) is the input/output. The difference between blocking and non-blocking is whether the system can accept other inputs as it goes from input to output

How is it different from Chrome?

  • There are no document, Window, and other browser apis in NodeJS
  • Built-in FS, process, HTTP API for operating files, reading process information, network communication and so on

What are the application scenarios?

  • Isomorphic Rendering, Next/NUxt
  • Build package, Webpack /gulp
  • Development tool, vsCode/electron

CommonJS module specification

The keyword

  • The require:
const game = require('./game');
Copy the code
  • Exports:
exports.port = 4000;
Copy the code
  • The module exports:
    • The module exports an empty object by default
    • If you want to change an exported object to a function, you can use the module.exports keyword
module.exports = function () {
	console.log('change :>> ');
};
Copy the code

Pay attention to

  • The exported variable points to the same reference as the variable introduced by require

  • Printing exports in a file importing lib.js is not the same as printing exports in lib.js

    // lib.js 
    exports.hello = 'test';
    exports.add = function(a, b) {
      return a + b
    }
    
    module.exports = function() {
      console.log('change :>> ');
    }
    
    setTimeout(() = > {
      console.log('exports :>> '.exports);
    }, 2000);
    
    // Exports to external :>> [Function (anonymous)]
    // internal exports :>> {hello: 'test', add: [Function (anonymous)]}
    Copy the code

    Exports is not bound to module.exports, which is only available in modules, once you assign a new value to exports.

Refer to the link

  • module.exports