A brief discussion on module specifications in Nodejs
This article will give you a detailed understanding of the module specifications in Nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Module specification is the basis for building a large-scale Node.js application, so it is very important; Node.js module specification is also the CommonJS module specification. Let’s take a brief look at it below. [Recommended learning: "nodejs Tutorial"]
CommonJS Module Specification
In the past, the only way to load JS files was through tag is introduced, what is the problem with this?
- When there are more scripts, you need to manually manage the loading order; the more scripts, the more difficult it is to manage.
- Logical calls between different scripts need to be done through global variables.
- How to reference the JS file when there is no
html
? This example is Node.js.
So Node.js has the CommonJS module specification, and Webpack is also compatible with the CommonJS writing method, allowing us to use the CommonJS specification to write front-end code.
The CommonJS module specification was initiated by the JavaScript community. It was applied and promoted on Node.js, and subsequently affected browser-side JavaScript.
require
require
is the API of the CommonJS module specification, used to introduce the files to be used. For example, import lib.js
:
require('./lib');
require
returns an empty object by default; create two new files with the following contents:
// lib.js console.log('this is lib'); // index.js console.log('start require') var lib = require('./lib'); // 默认返回一个空对象 console.log('end require', lib);
to run Take a look: node index.js
It can also mount some attributes through exports
: strings, functions , object and other types of data.
Add some code in lib.js
console.log('this is lib') exports.hello = "world" exports.add = function (a, b) { return a + b; } exports.obj = { hello: "Node" }
It seems that under the CommonJS module specification, it has a ## by default #exports Such an empty object.
require returns such an object, what happens if you modify and add its attributes?
// index.js // 既然 require 返回一个对象,那么修改和添加属性会怎么样呢? lib.hello = 'node'; lib.update = '1234';
// lib.js setTimeout(function() { console.log(exports) }, 500)
500ms to
lib.js. Therefore, you must pay attention to this copy problem when exporting through
exports. Some students may have seen this paragraph:
The CommonJS module outputs a shallow copy of a value, and the ES6 module outputs a reference to the value. So what's going on?
require can also return data through
module.exports, and the data type is not limited, for example, returning a function:
// lib.js console.log('this is lib') exports.hello = "world" exports.add = function (a, b) { return a + b; } exports.obj = { hello: "Node" } // setTimeout(function() { // console.log(exports) // }, 500) module.exports = function minus(a, b) { return a - b; }
lib returns the output
minus function.
when require a module,
module.exports has a higher priority than
exports, if specified If module.exports
is specified, the object specified by
module.exports will be used. If
module.exports is not specified,
exports## will be used. # Object.
npm
I believe everyone is familiar with it, so here is just a brief introduction.
is the package management tool for Node.js. When you install Node.js, it will come with npm
. Packages are Node.js modules written by others. In our daily development, we often use some packages developed by others and placed on the Node.js server.
Initialization: npm init
, just press Enter during initialization, and then a package.json
file will be generated; or execute Command npm init -y
, this will generate a default package.json
file, the properties inside are the same as executing npm init
and pressing Enter.
The content of the file is as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}</pre><div class="contentsignin">Copy after login</div></div><ul><li>下载安装依赖包 <code><packageName>
:npm install <packageName>
;如果想要全局安装则添加 -g
:npm install <packageName> -g
。如安装 glob
包:npm install glob
npm uninstall <packageName>
。比如安装 express
包,安装成功会生成一个 node-modules
文件夹,我们下载的包就放在这个文件里面:
如果使用 npm
安装依赖包的速度很慢,可以使用淘宝镜像 cnpm
来安装,镜像是指它把国外 npm
的包做一层复制然后映射到国内的服务器上面,这样不用山长水远去国外拉包,速度会快很多。
安装 cnpm
:
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm
的使用和 npm
类似:cnpm install <packageName>
。
那如果你觉得 cnpm
不够正宗,不想长期使用,但有些包下载又确实慢了,可以临时使用镜像,比如安装 express
:
npm install express --registry=https://registry.npm.taobao.org
--registry=
是指定下载地址的意思,例如一些公司可能有自己的依赖包服务器,那么可以通过将这个地址指向公司的服务器地址来更快的下载依赖包。
而 cnpm
本身其实是 npm
的一个别名,使用 cnpm
的时候会自动帮我们加上后面的参数 --registry=https://registry.npm.taobao.org
,然后通过镜像地址来下载依赖包。
另外,npm 使用遇到问题可以登录 官网 寻找解决办法:
总结
- Node.js 的模块规范就是 CommonJS 模块规范。
- CommonJS 模块规范通过
require()
加载模块,默认返回一个对象,可以通过设置exports
或module.exports
设置模块返回的数据。 - Node.js 的包管理工具是 npm,可通过使用镜像 cnpm 来提高下载速度。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of A brief discussion on module specifications in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.
