Implementation of built-in modules and custom modules in Node.js

Implementation of built-in modules and custom modules in Node.js

1. Commonjs

  • Commonjs is a custom module in nodejs
  • The Commonjs specification was proposed to make up for the defect of JavaScript having no standards and provide a standard library similar to the back-end language. In other words, commonjs is a modular standard, and nodejs is the modular implementation of commonjs. In nodejs, except http, url, fs, etc., they are all built-in modules of nodejs and can be used directly.
  • Implementation of custom modules in commonjs:
  • In nodejs, public functions are extracted into separate js files as modules, which cannot be accessed from the outside (similar to the private properties and methods of the backend); if you want to use the module, you must expose the properties or methods in the module through exports or module.exports. Use require to import the module where needed.

2. Two solutions for module export

Solution 1

let str={};
module.exports=str;

Solution 2

let str={};
exports.A=str;

3. Writing custom modules

common.js

// Built-in modules and custom modules in node // The module exports two solutions let str={};
module.exports=str;
exports.A=str;

// To import a module, use require("") to load the module let todo = require("./todo"); // The suffix can be omitted console.log(todo);

todo.js

module.exports={
   name:"Zhang San",
   sleep:function(){
       console.log("sleep");
   }
}

or

module.exports={
   name:"Zhang San",
   sleep:function(){
       console.log("sleep");
   }
}
  • When requiring() in node, you can directly write the name when loading a module, but it must be loaded under the dependency and a configuration file must be generated.
  • Enter the dependency file in the terminal and install the configuration file
  • Nodejs can automatically find files under the node_modules file: If there is a folder under the node_modules file, you can enter this file with cd and use the command cnpm init --yes to install the package.json file of the current file and directly request require("name");

Case 1

common.js

// To import a module, use require("") to load the module let todo = require("./todo"); // The suffix can be omitted console.log(todo);

// When requiring() in node, you can directly write the name when loading a module, but it must be loaded under the dependency, and a configuration file must be generated // Enter the dependency file in the terminal and install the configuration file let fetch=require("Fetch");
console.log(fetch);
fetch.get("http://www.zjm.com");

Fetch.js

module.exports={
   get(url){
       console.log(url);
   }
}

Case 2

common.js

let Axios = require("Axios");
let url = "https://autumnfish.cn/search";
let data = { keywords: 'Xi'an' };
const http = require("http");
let app = http.createServer((req, res) => {
   res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
   Axios.get(url, { params: data }).then((result) => {
       res.write(result);
       res.end();
   });
});
app.listen(8080)

Axios.js

const http = require("http");
const https = require("https");
//Conversion method let change = (args) => {
   let str = "?";
   for (let key in args) {
       str += key + "=" + args[key];
       str += "&";
   }
   return str.slice(0, str.length - 1);
}
module.exports = {
   get(href, { params }) {
       return new Promise((resolve, reject) => {
           href += change(params);
           https.get(href, (res) => {
               let { statusCode } = res;
               let error;
               if (statusCode != 200) {
                   error = new Error('Request Failed.\n' +
                       `Status Code: ${statusCode}`);
               }
               if (error) {
                   console.error(error.message);
                   // Consume response data to free up memory
                   res.resume();
                   return;
               }
               //Set the response encoding res.setEncoding("utf8");
               let alldata = "";
               //Monitor datares.on("data", (info) => {
                   alldata += info;
               })
               res.on("end", () => {
                   let data =alldata;
                   resolve(data);
               })
           });
       });
   },
   post() {

   }
}

This is the end of this article about the implementation of built-in modules and custom modules in Node.js. For more relevant Node.js built-in modules and custom modules, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief introduction to the front-end progressive framework VUE
  • Detailed explanation of vuex progressive tutorial example code
  • Spring Boot Web Application Configuration Detailed Explanation
  • Sample code for creating a web application using Spring Boot
  • NodeJs high memory usage troubleshooting actual combat record
  • Detailed explanation of using Nodejs built-in encryption module to achieve peer-to-peer encryption and decryption
  • How to make full use of multi-core CPU in node.js
  • Summary of some tips for bypassing nodejs code execution
  • How to Develop a Progressive Web App (PWA)

<<:  Detailed explanation of MySQL user rights verification and management methods

>>:  How to configure Linux CentOS to run scripts regularly

Recommend

Detailed explanation of nginx installation, deployment and usage on Linux

Table of contents 1. Download 2. Deployment 3. Ng...

Pull-down refresh and pull-up loading components based on Vue encapsulation

Based on Vue and native javascript encapsulation,...

Vue custom v-has instruction, steps for button permission judgment

Table of contents Application Scenario Simply put...

Common ways to optimize Docker image size

The Docker images we usually build are usually la...

Implementation of MySQL master-slave status check

1. Check the synchronization status of A and B da...

A quick guide to Docker

Docker provides a way to automatically deploy sof...

Detailed explanation of the core concepts and basic usage of Vuex

Table of contents introduce start Install ① Direc...

Learn Hyperlink A Tag

ask: I have styled the hyperlink using CSS, but i...

Vue routing to implement login interception

Table of contents 1. Overview 2. Routing Navigati...

JavaScript super detailed implementation of web page carousel

Table of contents Creating HTML Pages Implement t...

Detailed explanation of the execution process of MySQL query statements

Table of contents 1. Communication method between...

How to implement JavaScript's new operator yourself

Table of contents Constructor new Operator Implem...

Tips on disabling IE8 and IE9's compatibility view mode using HTML

Starting from IE 8, IE added a compatibility mode,...