Table of Contents
CommonJS Module Specification
require
总结
Home Web Front-end JS Tutorial A brief discussion on module specifications in Nodejs

A brief discussion on module specifications in Nodejs

Jun 09, 2021 am 10:47 AM
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.

A brief discussion on module specifications in Nodejs

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');
Copy after login

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);
Copy after login

to run Take a look: node index.js

A brief discussion on module specifications in Nodejs

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" }
Copy after login

A brief discussion on module specifications in Nodejs

It seems that under the CommonJS module specification, it has a ## by default #exports Such an empty object.

So since

require returns such an object, what happens if you modify and add its attributes?

// index.js
// 既然 require 返回一个对象,那么修改和添加属性会怎么样呢?
lib.hello = 'node';
lib.update = '1234';
Copy after login
// lib.js
setTimeout(function() {
  console.log(exports)
}, 500)
Copy after login

A brief discussion on module specifications in Nodejs

You can see that the printed content has changed after adding a

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?

It turns out that

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;
}
Copy after login

A brief discussion on module specifications in Nodejs

You can see:

lib returns the output minus function.

That is,

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

npm

I believe everyone is familiar with it, so here is just a brief introduction.

npm

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.

npm

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.

A brief discussion on module specifications in Nodejs

package.json

The content of the file is as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>{ &quot;name&quot;: &quot;node&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot; }, &quot;author&quot;: &quot;&quot;, &quot;license&quot;: &quot;ISC&quot; }</pre><div class="contentsignin">Copy after login</div></div><ul><li>下载安装依赖包 <code><packageName>npm install <packageName>;如果想要全局安装则添加 -gnpm install <packageName> -g。如安装 glob 包:npm install glob

  • 卸载依赖包的命令是 npm uninstall <packageName>
  • 比如安装 express 包,安装成功会生成一个 node-modules 文件夹,我们下载的包就放在这个文件里面:

    A brief discussion on module specifications in Nodejs

    如果使用 npm 安装依赖包的速度很慢,可以使用淘宝镜像 cnpm 来安装,镜像是指它把国外 npm 的包做一层复制然后映射到国内的服务器上面,这样不用山长水远去国外拉包,速度会快很多。

    安装 cnpm

    npm install -g cnpm --registry=https://registry.npm.taobao.org
    Copy after login

    cnpm 的使用和 npm 类似:cnpm install <packageName>

    那如果你觉得 cnpm 不够正宗,不想长期使用,但有些包下载又确实慢了,可以临时使用镜像,比如安装 express

    npm install express --registry=https://registry.npm.taobao.org
    Copy after login

    --registry= 是指定下载地址的意思,例如一些公司可能有自己的依赖包服务器,那么可以通过将这个地址指向公司的服务器地址来更快的下载依赖包。

    cnpm 本身其实是 npm 的一个别名,使用 cnpm 的时候会自动帮我们加上后面的参数 --registry=https://registry.npm.taobao.org,然后通过镜像地址来下载依赖包。

    另外,npm 使用遇到问题可以登录 官网 寻找解决办法:

    A brief discussion on module specifications in Nodejs

    总结

    • Node.js 的模块规范就是 CommonJS 模块规范。
    • CommonJS 模块规范通过 require() 加载模块,默认返回一个对象,可以通过设置 exportsmodule.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!

    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)

    The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

    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.

    Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

    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.

    How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

    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.

    What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

    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

    What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

    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.

    Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

    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.

    Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

    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.

    Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

    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.

    See all articles