background

Before you can understand a technology, it’s important to understand its background. Here IS a excerpt from the Chinese website of Node.js.

JavaScript is a programming language created in Netscape as a scripting tool for manipulating web pages in its browser, Netscape Navigator.

Part of Netscape’s business model is to sell Web servers, including an environment called Netscape LiveWire that creates dynamic pages using server-side JavaScript. Unfortunately, Netscape LiveWire wasn’t very successful, and server-side JavaScript didn’t take off until Node.js was introduced.

One of the key factors driving the rise of Node.js is timing. Only a few years ago, JavaScript began to be seen as a more serious language, thanks to “Web 2.0” applications (Flickr, Gmail, etc.) that introduced the world to modern experiences on the Web.

JavaScript engines are getting better as many browsers compete to provide the best performance for users. The development teams behind the major browsers are working hard to provide better support for JavaScript and to find ways to make JavaScript run faster. Thanks to this competition, the V8 engine used by Node.js (also known as Chrome V8, the open-source JavaScript engine for the Chromium project) has been significantly improved.

Node.js happened to be built in the right place at the right time, but luck isn’t the only reason it’s popular today. It has introduced a lot of innovative thinking and approaches to JavaScript server-side development that have already helped many developers.

A brief overview of the above statement is: front-end developers can use javascript to develop server-side applications, which allows only front-end javascript to be issued before, and reaches the realm of Web applications. After that, node.js based tools and frameworks emerge in an endless stream, such as vue.js framework, Webpack packaging tools and so on, which greatly improve the development efficiency of front-end developers, but also optimize the performance of the server, and bring better user experience.


What is a node. Js?

Node.js is a javascript runtime environment that provides basic functionality and built-in apis. Take a look at the following two images to distinguish the differences between the javascript runtime environment in the browser and the javascript runtime environment in Node.js.

The difference between Node.js and Google Chrome is that they have different built-in apis. That’s why Node.js can be used for Web applications, because these built-in apis can manipulate files, databases, create Web servers, and so on. The javascript runtime environment on the browser, on the other hand, can only operate on DOM and BOM objects.

In this way, Node.js is a great boon to front-end developers. Before Node.js was born, if a front-end developer wanted to develop server-side, it would have to learn back-end related development languages, such as Java, PHP, etc., which greatly increased the learning burden of front-end developers. So a front-end developer can do a lot more for himself if he learns node.js.


What is modularity?

I think it’s important to understand the concept of modularity before learning about Node.js’s built-in apis or third-party libraries, so let me talk about modularity in some detail.

First ask yourself, why modularity?

Before I learned about modularity, I had no idea why bother writing multiple JS files when I could write all my JS code in one script tag.

This is because in the business development, in most cases, it is a team to develop a project, each member of the team is responsible for a certain part of the business development, and in the end, everyone’s code is integrated to complete the project development. Here exposed that if you do not use modular development, it will cause global variable pollution, leading to the normal operation of the program, reduce the efficiency of development and code maintenance, and even caused a waste of resources!

With the idea of modularity, you don’t have to worry about contamination of global variables, you can declare variables ^^ as you like (just kidding), and improve the reuse and maintainability of code.


So how do you load modules?

Since Node.js follows the CommonJS module specification, modules are loaded using the require () method instead of import! Now let’s use an example of how to load a module using a file read/write operation. (Actually very simple ^^).

const fs=require('fs');// Import the built-in API FS module

fs.readFile('./node/file/zz.txt'.'utf8'.function(err,data){
    console.log(err);
    console.log(data);
})

fs.writeFile('./node/file/zz.txt'.'Hello Node.js!!! '.function(err,data){
    if(err){
      return  console.log('Failed to write data:${err}`)}else
        console.log('Write data successfully:${data}`)
})

fs.writeFile('./node/file/text.txt'.'Hello Node.js'.function(err,data){
    if(err){
        return  console.log('file failed to write:${err}`)}else
        return  console.log('File write succeeded:${data}`)})Copy the code
fs.writeFile(file, data[, options], callback)
/* 1. File is a mandatory parameter that specifies the address of the file to which data is to be written (either relative or absolute), but it is better to use the path.join() method of the path module to specify the path to the file, otherwise the file may not be accessed. 2. Options is an optional argument that specifies the format of the data to be written. 4. Callback is a mandatory argument that calls the callback function */ when the write operation is complete
fs.readFile(file,[,options], callback)
/* 1. File is a mandatory parameter, specifying the address of the file to which the data is to be written. Options is an optional parameter, specifying the format of the data to be written
Copy the code

Assuming the above code executes successfully, do you know the output order on the console?

I’m sorry, but the output of the above order, we are not sure, because it is an asynchronous read and write operations, when javascript code parsing engine performs to read and write operations, will they hang on the main thread, wait until they finished, will send the callback function into the task queue, stack synchronization tasks such as complete when all, Execute the callbacks in the task queue in sequence. We do not know the size of these read/write files, it is possible that the first file has a large amount of data, so it may be the last to execute the callback function!

To summarize, when a read/write operation depends on another read/write operation, it should be written to the callback function of the other read/write operation. (T_T, which causes the problem of callback hell….) Balabala, who wants to solve the problem of callback hell, can check out the relevant information of Promise!


How can members of a module be shared externally?

Node. js allows users to share module members in two different ways: module.exports and exports.

Exports: Module. Exports: Module. Exports: Module.

It is recommended that you try not to mix them in a single module, as this can cause some errors, and I will describe what errors can cause.

//ab.js
let a=18;
let b="White";
let c='black';
exports.c=c;
module.exports={
    a,
    b,
}
Copy the code
//index.js
const  a =require("./ab.js")
console.log(a)/ / {a: 18, b: "small white"}
Copy the code

Module. exports and exports refer to the same object. Why does object A not have property C?

let a=18;
let b="White";
let c='black';
exports=module.exports;
exports.c=c;
module.exports={
    a,
    b,
}
Copy the code

Modify the above ab.js file slightly, so that you understand it! Module. exports () {/ / module. Exports () {/ / module. Exports () {/ / module. Exports () {/ / module.

To summarize: the require() method always imports objects to which module.exports points


Today I will stop here, next I will write an article on NPM package management tools, if there are any mistakes hope that you pointed out ^^.