search
HomeWeb Front-endJS TutorialA 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.

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

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

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" }

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';
// lib.js
setTimeout(function() {
  console.log(exports)
}, 500)

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

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: <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><ul> <li>下载安装依赖包 <code><packagename></packagename>npm install <packagename></packagename>;如果想要全局安装则添加 -gnpm install <packagename> -g</packagename>。如安装 glob 包:npm install glob

  • 卸载依赖包的命令是 npm uninstall <packagename></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

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

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

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

    --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
    This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

    JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

    C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

    C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    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

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)