Writing in the front

This is the fourth installment of the Node.js Getting Started series, which covers topics in the form of structured brain maps, text explanations, summaries, practice examples, and interview questions. While studying this series won’t get you to the senior level right away, the knowledge you gain is a building block on your way to the senior level.

At the same time, golden nine silver ten arrived, a lot of friend also opens up a trip to the interview, to help you get satisfied with the offer, I will take the interview friends, every day in every company of bo, sorting documents, within the group of junior partner to share with you, review to avoid detours, to help more friends find the front end of the interview hot spots, Look for weaknesses in your knowledge. If you’re interested, there are surprises in the second article in this series.

The last review

Last time we talked about module concepts inside Node.js, REPL, and the origins of front-end modularity and its relationship to Node.js.

If you are reading this article for the first time, it is highly recommended that you start with the first section. You will get a lot more out of this series. There is no exaggerated title, but the content is broad enough to give you a different interpretation. At the same time, each article is not many words, 5-10 minutes to read, if the time is not enough, you can click to follow or like, in the future, you can find this series of articles in the “dynamic”.

Please click here to skip to the chapters you need to read: Getting Started node.js Getting Started Series (1) Features, Application Scenarios, and Front-end Pain Points Solved Node.js Getting Started Series (2) Modules, REPL

Node.js has the “everything module” tagline, much like the “everything object” tagline in front-end JavaScript. This feature has both advantages and disadvantages. The advantage is that everything is a unified concept, easy to learn and memorize; The downside is that a lot of times this concept is confusing, just like in the front end JavaScript, Array and String are objects, which can be confusing for a while. With further study, the confusion will gradually disappear. Let’s begin this section.

Learning objectives in this section

Two goals: 1) How to debug the development program? 2) What methods and variables are available in Node.js

Learn the table of contents in this section

What is the Node.js console? How do I debug an application using the console?

The global scope of Node.js and the global functions and variables provided by Node.js

3. Relevant interview test points in this section

Summary of four sections

Node.js event mechanism

6 at the end of the article

What is the Node.js console? How do I debug an application using the console?

In Node.js, we talked about node.js modules. One of the modules is the console module.


This module is a built-in object that has many methods to output information for debugging, just like the console built-in object we use in client-side JavaScript, and can be remembered together. It can be used either to write in the module and output when the module executes, or to write directly in the REPL, out of the file module. The following list of methods it has, in the use of comparison can be found.


extension

In section 2 we looked at the REPL, an interactive interpreter that provides a debugging and runtime environment, and in this section we looked at the Console module, which also provides debugging functionality. What’s the difference? Do we have two debugging tools?

Let’s start by looking at what they are: In section 2, when we demonstrated the REPL example, we saw that the REPL can execute expressions, access the last record, and also provide some basic instructions. The REPL provides a runtime environment. Console is a built-in module of Node.js that can be used in JS files or printed directly in the REPL.

So the relationship between the REPL and Console is that one is the runtime and the other is the debug tool, and the debug tool depends on the runtime.

The global scope of Node.js and the global functions and variables provided by Node.js

Node.js global scope

In section 1, we explained that the Node.js module solved the problem of modular private scope. Each module has a private scope. External objects cannot directly access the internal scope of the module, only objects exported through exports can be accessed. Although Node.js emphasizes the importance of modules, it still designs the concept of global functions, which can be accessed and used within any module within the global scope to increase code reusability. This global namespace is called global, which is an object. Many properties, methods, and classes are mounted on global. To see what is mounted in this global namespace, start the REPL environment and type the following:

console.log(global)

Copy the code

Note that there is only one global namespace. If methods and variables are not globally common, do not mount them to the global namespace. Also, avoid overwriting global methods and properties if you don’t have to.

Node.js provides global functions and variables

1) the setTimeout and clearTimeout

SetTimeout is similar to setTimeout in JavaScript on the client side. It means that from now on, the callback function will be executed after the specified time. ClearTimeout cancels the call to the callback function. The syntax is as follows:

setTimeout(callback, ms, [arg], [...] )

Copy the code





2) setInterval and clearInterval functions

SetInterval is similar to setInterval in JavaScript on the client side, which means that the callback function is executed at specified intervals. ClearInterval uncalls the callback function. The syntax is as follows:

setInterval(callback, ms, [arg], [...] )

Copy the code


3) Unref method and REF method

The setTimeout and setInterval methods both return a timer object. Node.js adds unref and ref methods to each of these two timer objects.

These two methods are not available in client-side JavaScript, so what are they useful for?

In simple terms, the unref method is used to cancel the setTimeout and setInterval callback functions. Ref does the opposite, resuming calls to callback functions.


const timer = setInterval(callback, ms, [arg], [...] SetTimeout and setInterval return a timer object



Timer.unref () // Cancel the execution of the callback function



Timer.ref () // Resumes the execution of the callback function

Copy the code


Summary UNref method and REF method:

1) The unref() and ref() methods are called from the object returned by the timer, mounted to the timer object; 2) The unref() and ref() methods cancel callback and restore callback only cancel and restore callback function in timer object, does not affect the existence of timer, to clear timer still use clearInterval or clearTimeout. 4) Unref () and ref() allow us to control from anywhere in the code when a timer executes a callback and when to cancel a callback

4) Global methods and properties associated with the REQUIRE module

Node.js follows the common.js standard specification and uses the require method when importing modules. The syntax is as follows:

const foo = require('.. /foo.js) // accepts a string pathname as an argument

Copy the code











const foo = require('foo') // Only a string name is passed without specifying the file type

Copy the code

The argument passed to require is an obscure file name. Node.js does not directly report an error, but has a set of lookup rules, summarized as follows:

  1. Load the file first with the priority of.js >.json >.node
  2. If package.json is available, load the file specified by the main property in package.json. * Without package.json, load the index.js file in that directory
Extension:

The React project uses cli scaffolding to build the front-end. When introducing components, it also omits the.js file suffix, but you can still find the corresponding file. The search principle is the same as here.


Resolve in Node.js, you can use the require.resolve function to query the filename of a module file with the complete absolute path as follows:

require.resolve('./testModule.js');

Copy the code

When executed at REPL, the output is the absolute path of the disk on which the module is located. Using this method to find custom modules yields a file name with a full absolute path, so what if you use this method for built-in modules? The answer is: just print the name


Note:

The require.resolve() method does not import the module, nor does it execute the in-module method, but simply looks for the complete absolute path to the module.

Use the require.cache object to view cached modules

The same module will be cached in memory after it is loaded for the first time. After that, multiple references to the same module will result in the same module, which will not cause multiple execution of the code in the module. You can view a list of currently cached modules using require.cache. The syntax is as follows. Type in the REPL:

console.log(require.cache)

Copy the code

You can view all cached modules. If we want to view a named module, we can use the following syntax:

console.log(require.cache[require.resolve('./testModule.js')])

Copy the code

One of the remaining problems is: because modules are cached after they are introduced, the modified modules will not be updated immediately in the imported files. How to solve this problem?

Here’s a solution:

What if we could delete cached modules where they need to be updated, and then reintroduce them?

This method involves two operations: deleting a module, importing a module; Introduce modules with require. What about deleting modules?

Fortunately, Node.js provides the delete keyword to delete cached modules. The syntax is as follows:

const testModule1 =require( './testModule.js') // The module is initially introduced and cached in memory



delete require.cache[require.resolve('./testModule.js'] // Delete the module from the cache



const testModule2 = require( './testModule.js'// Reload the module again



Copy the code
Development:

In a real project where the latest module is required, this mechanism can be encapsulated as a method that guarantees the use of the latest changed module by passing in the module path parameter and calling the method at a specified place.

Global variables associated with the file system module

Two file module-related variables are defined in Node.js, one is __filename and the other is __dirname.

The __filename command is used to get the complete absolute path filename of the current module file. The syntax is as follows:

console.log(__filename)

Copy the code

__dirname is used to get the full absolute path to the directory where the current module file resides. The syntax is as follows:

console.log(__dirname)

Copy the code
Confused:

The require.resolve() method gets the full absolute path to the current module file directory, and __filename does the same. Summarized below

3) require. Resolve () is a method mounted to the require object. __filename is a global variable, one is a method, the other is a variable. 3) require. Resolve (); __filename () does not need to be passed as a parameter. Resolve () requires. Resolve () is stronger than __filename, which is the absolute path to the current module. 4) In real projects, it is usually easier to use path changes based on __filename and then switch to another file path than require.resolve().

Iii. Relevant interview points in this section

1) What are your debugging methods for node.js development? 2) What is the relationship between the REPL and console? 3) How do you choose require.resolve() and __filename? 4) What problems will front-end modularization bring? 5) What are the node.js lookup rules when importing modules without specifying file suffixes?

4. Summary of this section

This section focuses on two things: the Console module and built-in methods and variables in the global scope. While these two pieces are not difficult, they extend a lot of knowledge in this article. The purpose of this article is to connect the front end of Node.js to the front end. The real interview will never directly ask you the concept, more will not directly ask the theory back is not familiar. Tools serve the business, how to use tools, where to use, how to use the level, how to solve problems, is the key to distinguish the primary and senior.

Five, the next period: Node.js event mechanism

Node.js is single-threaded, non-blocking and event-driven, which determines the important role of event mechanism in Node.js. At the same time, this is not something that can be explained in one or two sentences.

So I’m going to talk about the event mechanism in detail in a separate section, and also reduce the burden of reading this section. Please stay tuned for updates, and we’ll talk about it in detail next time.

Six, at the end of the article

Only write understandable, readable, valuable technical articles;

After reading, if you feel you have gained something, click “like” and pay attention to it, the platform will recommend more high-quality articles for you.

Finally, I will serialize the series “Learn webpack from Scratch”, if you are also interested, welcome to read it.