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

CSS implements five common 2D transformations

2D transformations in CSS allow us to perform som...

Summary of 3 ways to lazy load vue-router

Not using lazy loading import Vue from 'vue&#...

Vue3 encapsulates the side navigation text skeleton effect component

Vue3 project encapsulation side navigation text s...

Use the sed command to modify the kv configuration file in Linux

sed is a character stream editor under Unix, that...

TypeScript decorator definition

Table of contents 1. Concept 1.1 Definition 1.2 D...

MySQL 8.0.23 Major Updates (New Features)

Author: Guan Changlong is a DBA in the Delivery S...

Teach you how to install mysql database on Mac

Download MySQL for Mac: https://downloads.mysql.c...

Display ellipsis effect when table cell content exceeds (implementation code)

illustrate In front-end development, you often en...

Steps to run ASP.NET Core in Docker container

There are too much knowledge to learn recently, a...

Vue+node realizes audio recording and playback function

Result: The main part is to implement the code lo...