search
HomeWeb Front-endJS TutorialHow to use node modules and npm package management tools

How to use node modules and npm package management tools

Jun 13, 2018 pm 05:42 PM
nodenpmmoduleModule management

This article mainly introduces the node module and npm package management tool. Now I will share it with you and give you a reference.

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 perform many functions on these parts. Good collaborative management. 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.

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 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 ;

Then we want to use these variables in http.js. Function or object, 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')

node Run this http.js node http.js

The running result is 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 you can use module .exports, but 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;

Then we want to use the variables, functions or objects of this class in http.js, which can be found in http.js Write the following code in:

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);

Then run the node http.js command in iTerm. The running result is as follows

Summary of the above:

In other words, there are two modes of cooperation between js files and js files:
1) In a certain js file, functions are provided 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;

package. There is a sharp angle in front of the version number in json, which means 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 node_modules folder has been created in the folder, and the libraries we need have been installed in the folder

2. Contents in the folder after installation

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

3. Create package.json

Then some dependencies of our project, version number , description, author, etc. 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. Attributes of module objects

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.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

ajax requests vue.js to render the page to load

How to solve the problem of page flashing when Vue.js displays data

How to set the title method of each page using vue-router

How to implement page jump in vue and return to the initial position of the original page

The above is the detailed content of How to use node modules and npm package management tools. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment