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

W3C Tutorial (3): W3C HTML Activities

HTML is a hybrid language used for publishing on ...

How to solve the Mysql transaction operation failure

How to solve the Mysql transaction operation fail...

Detailed tutorial on installing Tomcat8.5 in Centos8.2 cloud server environment

Before installing Tomcat, install the JDK environ...

How to install ZSH terminal in CentOS 7.x

1. Install basic components First, execute the yu...

How to process blob data in MySQL

The specific code is as follows: package epoint.m...

Embed player in web page embed element autostart false invalid

Recently, I encountered the need to embed a player...

Implementing carousel with native JavaScript

This article shares the specific code for impleme...

MySQL study notes on handling duplicate data

MySQL handles duplicate data Some MySQL tables ma...

Summary of the minesweeping project implemented in JS

This article shares the summary of the JS mineswe...

A brief introduction to Tomcat's overall structure

Tomcat is widely known as a web container. It has...

Nginx tp3.2.3 404 problem solution

Recently I changed Apache to nginx. When I moved ...

How to solve the element movement caused by hover-generated border

Preface Sometimes when hover pseudo-class adds a ...

Building FastDFS file system in Docker (multi-image tutorial)

Table of contents About FastDFS 1. Search for ima...

Code analysis of synchronous and asynchronous setState issues in React

React originated as an internal project at Facebo...

Install and configure MySQL under Linux

System: Ubuntu 16.04LTS 1\Download mysql-5.7.18-l...