In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use Node.js module and npm package manager". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use the Node.js module and the npm package manager.
Require function
Function: load another module in the current module
Syntax: require (module name)
Module classification
In Node.js, modules can be divided into three main categories, as follows:
1. Custom module: a module with a specific function written in a project is a custom module.
When the submodule does not expose data, it returns an empty object instead of undefined.
To reference a custom module, you must add. / [for example: require (". / 01.js")] to the path, because Node.js is not the current directory by default, but node_modules.
two。 Third-party modules: modules developed by third-party programmers or companies that need to be installed before use and can be installed through the NPM package manager.
3. System module: Node.js comes with the system module, do not need to install and download, you can directly reference [such as: fs,http,url, etc.].
Third-party module
If you want to use a third-party module, you must install it first, taking jQuery as an example, as follows:
1. Install a third-party module
Before installation, it is as follows:
Install through the installation command [npm install jquery], as follows:
After a successful installation, the node_modules folder is automatically created in the program directory, as shown below:
two。 Introduce a third-party module
When the installation is successful, you can refer to it directly in the program, as follows:
Var jquery = require ("jquery"); console.log (jquery.toString ()); 3. Sample test
Test on the command line to reference a third-party module, as follows:
Note: the reason for the error in the example is that jQuery is a module library on the browser side, so server-side calls are not supported. This is just a demonstration of a call example.
System module
The system module is a module with specific functions that comes with Node.js, which does not need to be installed and can be used directly. Take the file module as an example, as follows:
First, create a test file, test.txt, with the following contents:
It is then called through the fs module that comes with Node.js, as follows:
Var fs = require ("fs"); fs.readFile ("test.txt", function (err,data) {console.log (data.toString ());})
The test example is as follows:
Considerations for require
An error will be reported when there is an error in the introduced module.
An error will also be reported when the introduced module path does not exist.
When the module is referenced repeatedly, it will only be loaded once [because the first time it is loaded, it will be stored in the cache, and the second time it will be loaded, it will first determine whether the cache exists, and if so, it will be assigned directly].
For the schematic diagram of the require loading module, please refer to the following figure:
Exports export object
Function: expose or export the data in the module that needs to be shared with other modules to the reference.
Grammar: exports. Property or function.
1. Exports example
The following example: exposes a user name and sayHi method to the reference.
Var username= "Little sixth Childs"; function sayHi () {console.log ("hi, Little Liuzi");} exports.username=username; exports.sayHi=sayHi;2. Exports precautions
When using exports, the considerations are as follows:
Exports is equivalent to module.exports and is a reference to module.exports with the same memory address. It can be determined in the following ways:
Exports is an object, and you can add properties and methods, but you cannot modify what exports points to. As follows:
Exports.sayHi=sayHi; exports=sayHi;// this syntax is incorrect and cannot be modified to point to module module objects
The most important thing in module is the exports object, as follows:
Module.exports is the real exposure object, and exports is just a reference to it.
Module.exports. Attribute = value
Module.exports. Method = function
Module.exports= object or function; / / Export object directly
Other properties of the module object:
The ID of the module.id module, which is the only path to the object.
The parent of the module.parent module.
Module.filename, the file name and path of the module.
The module.children submodule, which is an array type.
Module.paths array type. A list of paths for the current module to find objects.
The specific details about the module object are as follows:
Package.json package description file
NPM [Node Package Manager] is a Node.js-based package management tool. In Node.js projects, the basic unit of JS is a single file, but complex modules are often made up of multiple sub-modules. For ease of management and use, we can call a large module consisting of multiple modules a package, and put all the sub-modules in the same directory. There needs to be an entry in all the sub-modules that make up a package, and the export object of the entry module is called the export object of the package. The entry module in the default package is index.js, or you can create a new package.json package description file in the package and set the main property to the entry of the module.
1. What is package.json?
Package.json is the package description file for the node.js project, describing the project in json format. Take the previously installed jQuery as an example, you can view the corresponding package.json file, as shown below:
{"_ from": "jquery", "_ id": "jquery@3.6.0", "_ inBundle": false, "_ integrity": "sha512-JVzAR/AjBvVt2BmYhxRCSYysDsPcssdmTFnzyLEts9qNwmjmu4JTAMYubEfwVOSwpQ1I1sKKFcxhZCI2buerfw==", "_ location": "/ jquery", "_ phantomChildren": {}, "_ requested": {"type": "tag", "registry": true, "raw": "jquery", "name": "jquery" "escapedName": "jquery", "rawSpec": "", "saveSpec": null, "fetchSpec": "latest"}, "_ requiredBy": ["# USER", "/"], "_ resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.0.tgz"," _ shasum ":" c72a09f15c1bdce142f49dbf1170bdf8adac2470 "," _ spec ":" jquery " "_ where": "D:\\ MyProject\\ DemoNodeJs", "author": {"name": "OpenJS Foundation and other contributors", "url": "https://github.com/jquery/jquery/blob/3.6.0/AUTHORS.txt"}," bugs ": {" url ":" https://github.com/jquery/jquery/issues"}, "bundleDependencies": false, "commitplease": {"nohook": true Components: ["Docs", "Tests", "Build", "Support", "Release", "Core", "Ajax", "Attributes", "Callbacks", "CSS", "Data", "Deferred", "Deprecated", "Dimensions", "Effects", "Event", "Manipulation" "Offset", "Queue", "Selector", "Serialize", "Traversing", "Wrap"], "markerPattern": "^ ((clos | fix | resolv) (e[ SD] | ing)) | ^ (refs?)", "ticketPattern": "^ ((Closes | Fixes) ([a-zA-Z] {2,} -) [0-9] +) | ^ (Refs? [^ #])"}, "deprecated": false "description": "JavaScript library for DOM operations", "devDependencies": {"@ babel/core": "7.3.3", "@ babel/plugin-transform-for-of": "7.2.0", "commitplease": "3.2.0", "core-js": "2.6.5", "eslint-config-jquery": "3.0.0", "grunt": "1.3.0" "grunt-babel": "8.0.0", "grunt-cli": "1.3.2", "grunt-compare-size": "0.4.2", "grunt-contrib-uglify": "3.4.0", "grunt-contrib-watch": "1.1.0", "grunt-eslint": "22.0.0", "grunt-git-authors": "3.2.0" "grunt-jsonlint": "1.1.0", "grunt-karma": "4.0.0", "grunt-newer": "1.3.0", "grunt-npmcopy": "0.2.0", "gzip-js": "0.3.2", "husky": "1.3.1", "insight": "0.10.1", "jsdom": "13.2.0" "karma": "5.2.3", "karma-browserstack-launcher": "1.4.0", "karma-chrome-launcher": "2.2.0", "karma-firefox-launcher": "1.1.0", "karma-ie-launcher": "1.0.0", "karma-jsdom-launcher": "8.0.2", "karma-qunit": "3.0.0" "load-grunt-tasks": "5.1.0", "native-promise-only": "0.8.1", "promises-aplus-tests": "2.1.2", "Q": "1.5.1", "qunit": "2.9.2", "raw-body": "2.3.3", "requirejs": "2.3.6" "sinon": "2.3.7", "sizzle": "2.3.6", "strip-json-comments": "2.0.1", "testswarm": "1.1.2", "uglify-js": "3.4.7"}, "homepage": "https://jquery.com"," Husky: {"hooks": {"commit-msg": "commitplease .git / COMMIT_EDITMSG", "pre-commit": "grunt lint:newer qunit_fixture"}}, "keywords": ["jquery", "javascript", "browser", "library"], "license": "MIT", "main": "dist/jquery.js", "name": "jquery" "repository": {"type": "git", "url": "git+ https://github.com/jquery/jquery.git"}," scripts ": {" build ":" npm install & & grunt "," jenkins ":" npm run test:browserless "," start ":" grunt watch " "test": "npm run test:slim & npm run test:no-deprecated & & npm run test:no-sizzle & & grunt & & grunt test:slow & & grunt karma:main & & grunt karma:amd", "test:amd": "grunt & & grunt karma:amd", "test:browser": "grunt & & grunt karma:main", "test:browserless": "grunt & & grunt test:slow" "test:no-deprecated": "grunt test:prepare & & grunt custom:-deprecated & & grunt karma:main", "test:no-sizzle": "grunt test:prepare & grunt custom:-sizzle & & grunt karma:main", "test:slim": "grunt test:prepare & & grunt custom:slim & & grunt karma:main"}, "title": "jQuery", "version": "3.6.0"} 2. How do I create a package.json file?
In node.js, you can create it according to the wizard. On the command line, change the directory to the directory where the program is located, and then enter the command [npm init] to open the package file creation wizard. As follows:
Fill in the corresponding information according to the installation steps of the wizard. After the above 7 steps, you can create the package file. After the package file is created successfully, it is shown below in the program directory:
{"name": "demonode", "version": "1.0.0", "description": "node example", "main": "index.js", "dependencies": {"jquery": "^ 3.6.0"}, "devDependencies": {}, "scripts": {"test": "echo\" Error: no test specified\ "& exit 1"}, "author": "Little six Childs" "license": "MIT"}
Note: if you create a default package.json file, you can use the [npm init-y] command to generate it with one click.
NPM Foundation 1. Common npm commands
The common npm commands are as follows:
Installation command: install the specified third-party package through the installation package command [npm install package name].
Abbreviated installation command: install the specified third-party package by using the command [npm I package name].
Specified version installation: install the specified version of the third-party package through the command [npm I package name @ verson]. The latest version is installed by default.
Global installation: install third-party packages globally through the command [npm I package name-g], which can be applied to all projects. Default global installation directory [C:\ Users\ login account\ AppData\ Roaming\ npm\ node_modules]
The installation also writes the dependency list: write to the dependency list in the package description file at the same time as the installation command [npm I package name-save].
The installation also writes to the development dependency list: write to the development dependency list in the package description file at the same time of installation by using the command [npm I package name-save-dev].
Find the package: find it through the command [npm serach package name].
Preview package: preview the contents of the package by using the command [npm view package name].
Uninstall packages: uninstall installed packages by using the command [npm uninstall package name].
Update package: update the package through the command [npm update package name].
2. Npm example
Take the installation and lookup of npm as an example, as follows:
Cnpm Foundation 1. What is cnpm?
Npm commands need to be downloaded and installed from foreign servers, the speed will be relatively slow, so in order to meet the needs of domestic applications, cnpm came into being. Cnpm is a software package image provided by Taobao that is updated synchronously with the npm server.
The current URL of cnpm is [https://npmmirror.com/package/cnpm], and a brief introduction to cnpm is as follows:
two。 Use cnpm
If you want to use cnpm, you can register with the command, as follows:
Npm install-g cnpm-- registry= https://registry.npmmirror.com
The cnpm command is used the same as npm, with a c prefix. The example is as follows:
Console output 1. Common console output
Node.js is used as a server-side runtime environment, so console output is also common, as shown below:
In Node.js, there are several types of console output:
Console.log (), which is the same as in the browser.
Console.dir (), which outputs directory information.
Console.error (), error message output.
Console.time (identifier) is used in conjunction with console.timeEnd (identifier) to calculate the execution time of a program.
Console.assert (conditional expression, output content); when the conditional expression is false, output content.
two。 Example of console output
Examples of common syntax for console output are as follows:
Console.log ("I am Little Liuzi"); console.dir ("I am Little Liuzi"); console.error ("Little Liuzi made a mistake"); console.time ("T1"); for (var iLiuzi)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.