Home Web Front-end JS Tutorial Analysis of node module and npm package management tool

Analysis of node module and npm package management tool

Jan 05, 2018 am 09:50 AM
node analyze Management tools

In Node.js, all functions are divided into modules and a complete module loading mechanism is provided, so we can divide the application into different parts and coordinate these parts well. manage. By writing various reusable codes in various modules, the amount of code in the application can be greatly reduced, the development efficiency of the application and the readability of the application code can be improved. Through the module loading mechanism, various third-party modules can be introduced into our applications. This article mainly introduces the node module and npm package management tool. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

In node.js, npm package management tool is provided for downloading various Node.js packages from third-party websites.

1. Module

1.1 Loading the module

In Node.js, all functions are divided into modules. , a Node.js application consists of a large number of modules, each module is a JavaScript file, to load the core module predefined in node.js, we only need require ('module name'), for example require ('http '), when introducing a third-party class library into our application, we need to specify the full path and file name of the file, such as require('./script/foo.js')

1.2 Accessing the module

1.2.1 Using the exports object to access

The variables, functions or objects defined in a module file are only valid within the module. When you need to reference these variables, functions or objects from an external module, you need to change the module. For example, create a testModule.js with the following code:


var testVar = "Can you see me now ? ";
var funName = function(name){
  console.log('My name is' + name);
}
exports.testVar = testVar ;
exports.funName = funName ;
Copy after login

Then we think To use these variables, functions or objects in http.js, you can write the following code in http.js:


var test1 = require('./testModule.js');
// 通过test1访问testModule.js模块内的testVar变量 和funName函数
console.log(test1.testVar)
test1.funName('Luckfine')
Copy after login

node Run this http.js node http.js

The running results are as follows


##1.2.2 Use the module.exports object to access

When you need to reference these variables, functions or objects from an external module, use the exports object or module.exports. However, when you need to define a class for the module, you can only use module.exports.

For example, define a testModule class with the following code in testModule.js:


var _name,_age
var name = '',age = 0;
var foo = function(name,age){
  _name = name ; 
  _age = age ;
}
// 获取私有变量_name的变量只
foo.prototype.GetName = function(name){
  return _name;
};
// 设置私有变量_name的变量值
foo.prototype.SetName = function(name){
  _name = name;
}
// 获取私有变量_age的变量只
foo.prototype.GetAge = function(age){
  return _age;
};
// 设置私有变量_name的变量值
foo.prototype.SetAge = function(age){
  _age = age;
}
foo.prototype.name = name;
foo.prototype.age = age;
module.exports = foo;
Copy after login

Then we want to use the variables of this class in http.js, For functions or objects, you can write the following code in http.js:


var foo = require('./testModule.js');
var myFoo = new foo('Luckfine',18);

console.log('获取修改前的私有变量值')
console.log(myFoo.GetName());
console.log(myFoo.GetAge());

console.log('修改私有变量');
myFoo.SetName('Baby');
myFoo.SetAge(16);

console.log('获取修改后的私有变量值')
console.log(myFoo.GetName());
console.log(myFoo.GetAge());


console.log('获取修改前的公有变量值')
console.log(myFoo.name);
console.log(myFoo.age);

console.log('修改公有变量')
myFoo.name = "Tom";
myFoo.age = 20;

console.log('获取修改后的公有变量值')
console.log(myFoo.name);
console.log(myFoo.age);
Copy after login
Then run the node http.js command in iTerm, and the running result is as follows


To summarize the above:


In other words, there are two modes of cooperation between js files and js files:

1) A certain A js file provides functions for others to use. Just expose the function; exports.msg=msg;
2) A certain js file describes a class. module.exports = People;

2. npm package management

npm is a package management tool that follows Node.js and can solve the problems of Node.js code deployment There are many problems. When we use npm to install some third-party libraries, the installation package will be placed in the node_modules folder in the directory where the npm command is run. If there is no node_modules in the current directory, the node_modules directory will be generated in the current directory. , and put the third-party libraries we need in node_modules.

So when installing, pay attention to the location of the command prompt.

Command to install third-party libraries npm install module name, if we need to install express, then we only need to enter npm install express

1 on the command line. Our dependent packages may be installed at any time Update, we always want to keep it updated, or maintain a certain version;

2. When the project gets bigger and bigger, there is no need to share the third-party modules we reference again when showing it to others.

So we can use package.json to manage dependent packages.


In cmd, use npm init to initialize a package.json file and generate a new package.json file by answering questions.


The purpose of generating package.json is that if we accidentally lose any dependencies, we can install the missing dependencies in package.json as long as we directly npm install;


There is a sharp angle in front of the version number in package.json, which indicates a fixed version, that is, the version I installed now is fixed;

For example, let’s create a new folder now

1. Create a new folder


We now need to install a third-party library express. First, enter this folder, open the command line, and enter npm install express'' here. After the command line is completed, we will see that a new one is created in the folder. node_modules folder, and the libraries we need have been installed in the folder

2. After installation, the contents of the folder

Then we If you need a package.json to manage our packages, you can enter npm init on the command line. At this time, you can answer the questions according to the prompts on the command line to create package.json

3. Create package.json

Then some dependencies, version numbers, descriptions, authors, etc. of our project can be managed accordingly through package.json.

##4. Package management


My package management content is relatively small, so under normal circumstances package.jaon has the following content


## 3. Module object Properties

This serves as a deeper understanding.

Inside the module file, you can access the following attributes of the current module.

module.id: Indicates the absolute path of the module file.

module.filename: The attribute value is the file name of the current module

module.loaded: The attribute value is a Boolean value. When the attribute value is false, it means that the module has not been loaded, otherwise it means that it has been loaded. .

module.parent: The attribute value is the parent module object of the current module, that is, the module object that calls the current module.

module.children: The attribute value is an array, which stores all the children of the current module. Module objects, that is, all module objects loaded in the current module.


Related recommendations:


Use nvm to manage different versions of node and npm

How to publish vue components to npm

About using NPM

The above is the detailed content of Analysis of node module and npm package management tool. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use MySQL database for forecasting and predictive analytics? How to use MySQL database for forecasting and predictive analytics? Jul 12, 2023 pm 08:43 PM

How to use MySQL database for forecasting and predictive analytics? Overview: Forecasting and predictive analytics play an important role in data analysis. MySQL, a widely used relational database management system, can also be used for prediction and predictive analysis tasks. This article will introduce how to use MySQL for prediction and predictive analysis, and provide relevant code examples. Data preparation: First, we need to prepare relevant data. Suppose we want to do sales forecasting, we need a table with sales data. In MySQL we can use

How to implement data statistics and analysis in uniapp How to implement data statistics and analysis in uniapp Oct 24, 2023 pm 12:37 PM

How to implement data statistics and analysis in uniapp 1. Background introduction Data statistics and analysis are a very important part of the mobile application development process. Through statistics and analysis of user behavior, developers can have an in-depth understanding of user preferences and usage habits. Thereby optimizing product design and user experience. This article will introduce how to implement data statistics and analysis functions in uniapp, and provide some specific code examples. 2. Choose appropriate data statistics and analysis tools. The first step to implement data statistics and analysis in uniapp is to choose the appropriate data statistics and analysis tools.

Real-time log monitoring and analysis under Linux Real-time log monitoring and analysis under Linux Jul 29, 2023 am 08:06 AM

Real-time log monitoring and analysis under Linux In daily system management and troubleshooting, logs are a very important data source. Through real-time monitoring and analysis of system logs, we can detect abnormal situations in time and handle them accordingly. This article will introduce how to perform real-time log monitoring and analysis under Linux, and provide corresponding code examples. 1. Real-time log monitoring Under Linux, the most commonly used log system is rsyslog. By configuring rsyslog, we can combine the logs of different applications

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Steps of statistical analysis Steps of statistical analysis Jun 28, 2023 pm 03:27 PM

Statistical analysis often refers to the process of sorting, classifying and interpreting collected relevant data. The basic steps of statistical analysis include: 1. Collect data; 2. Organize data; 3. Analyze data.

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Case analysis of Python application in intelligent transportation systems Case analysis of Python application in intelligent transportation systems Sep 08, 2023 am 08:13 AM

Summary of case analysis of Python application in intelligent transportation systems: With the rapid development of intelligent transportation systems, Python, as a multifunctional, easy-to-learn and use programming language, is widely used in the development and application of intelligent transportation systems. This article demonstrates the advantages and application potential of Python in the field of intelligent transportation by analyzing application cases of Python in intelligent transportation systems and giving relevant code examples. Introduction Intelligent transportation system refers to the use of modern communication, information, sensing and other technical means to communicate through

See all articles