Introduction to module definition in nodejs
This article mainly introduces the module definition method in nodejs, and analyzes the principles of nodejs modules, common modules and corresponding definition methods in the form of examples. Friends in need can refer to it
The examples in this article describe nodejs Medium module definition method. Share it with everyone for your reference, the details are as follows:
1. Module definition
The so-called module of nodejs is a file! A .js file is a nodejs module. There is a one-to-one correspondence between modules and files, so the reference module is require('file path').
For example:
var circle = require('./circle.js'); console.log( 'The area of a circle of radius 4 is ' + circle.area(4));
This is named foo.js
var PI = Math.PI; exports.area = function (r) { return PI * r * r; }; exports.circumference = function (r) { return 2 * PI * r; };
This is named circle.js
The two js code files are placed in the same folder.
If you want to reference modules in other folders, write the path directly. The path format here is the same as that of Linux: /../../.js This is the absolute path, ../.js is the upper layer, and ./.js is the current path.
You need to pay attention to the difference between exports and module.exports here: exports is actually just a reference to module.exports (just like a=2, b=a, b just refers to a, when b=c , b no longer points to a), so that you can understand the meaning of the official website (if you want to declare the root of exports as a function, or you want to generate an object, then please use module.exports instead of exports)
2. Circular reference
a.js:
console.log('a starting'); exports.done = false; var b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done');
b.js:
console.log('b starting'); exports.done = false; var a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done');
main.js:
console.log('main starting'); var a = require('./a.js'); var b = require('./b.js'); console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
See, this a.js and b.js two reference each other. Will this cause an infinite loop? No, this is just that one module has not been loaded, that is, part of a module is unavailable. Like here, a.js is loaded first, but while loading a.js, a.js loads b.js. At this time, a.js is in a stagnant state, only the data in front of require is loaded, and for b.js It will always be loaded. The following is the result of the operation:
$ node main.js main starting a starting b starting in b, a.done = false b done in a, b.done = true a done in main, a.done=true, b.done=true
3. Core module
The so-called core module is actually developed by nodejs Public packages, just like Java's public packages. To access the core module, just require('file name'), so you can access it. In fact, the public module package is placed under node_modules\npm\lib installed by nodejs.
4. File module
When there is no exact match for the so-called reference, nodejs will first use the extension: .js, .json, and then .node. . The js file is a JavaScript file, .json will be parsed in json format, and .node will be loaded as an additional module using dlopen
It is also important to note here that when there is no '/' or './' When modifying symbols, the module is loaded in node_modules. As for where this file is, please see below.
5.node_modules folder
If there is no format symbol qualification such as '/' '../' './' when referencing the module, then it uses The search method is as follows: Suppose your file is in '/home/ry/projects/foo.js' and it references require('bar.js')
, then the search method for bar.js is as follows:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules /bar.js
That is, starting from the current roadbed, add the node_modules folder to the parent directory step by step as the module address.
require('example-module/path/to/file')
This kind of reference is the same as require('bar.js')
.
6. Reference the module by the folder name
It can be roughly divided into two types: 1) Write the package.json file. This file is written in the root directory of the project. Its form is as follows:
{ "name" : "some-library", "main" : "./lib/some-library.js" }
The require('./some-library') written like this actually means
require('./some-library/lib/some-library.js')
2) Directly agree to load the index.js or index.node file. Same as the require above, the loading may be as follows:
./some-library/ index.js
./some-library/index.node
7. Cache
Multiple references to a module will only be loaded once . Just like the static keyword modification in java. However, it is worth noting that when you require('foo')
, this form does not necessarily guarantee that the same file will be referenced every time (because you may reference it in different folders) .
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Learning about the cluster module in Node
Introduction to using Angular with Node.js
About node.js’s method of reading and writing system files and directories based on the fs module
##
The above is the detailed content of Introduction to module definition 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.
