node require what does it mean
require in node is a function that accepts a parameter, the formal parameter is named id, and the type is String; the require function can import modules, JSON files, and local files; the module can be accessed from Exported from "node_modules", "local module" or "JSON file", the path will be for the "__dirname" variable or the current working directory.
The operating environment of this tutorial: Windows 7 system, nodejs version 18.4.0, Dell G3 computer.
What does node require mean?
The specific usage of the require function in Nodejs
Instructions
This article refers to the Node official website document version. v11.12.0.
This article mainly analyzes the results obtained when require imports JSON and js files in Nodejs. It also briefly touches on the usage of module export module.exports and exports in Nodejs.
Introduction
In the process of reading the webpack source code, I saw the following line of code:
const version = require("../package.json").version
So This leads to the study of require in Nodejs.
require introduction
In the Node.js documentation, the relevant documentation for require is in the Modules directory and belongs to the Nodejs module part of the system.
require is a function. This conclusion can be verified through typeof or Object.prototype.toString.call():
console.log(require) // 输出:Function console.log(Object.prototype.toString.call(require) // 输出:[object Function]
By printing require directly, you can find that there are several static properties mounted under the require function. These static properties can also be The relevant instructions can be found directly in the official documentation of Nodejs:
{ [Function: require] resolve: { [Function: resolve] paths: [Function: paths] }, main: Module { id: '.', exports: {}, parent: null, filename: '/Users/bjhl/Documents/webpackSource/index.js', loaded: false, children: [], paths: [ '/Users/bjhl/Documents/webpackSource/node_modules', '/Users/bjhl/Documents/node_modules', '/Users/bjhl/node_modules', '/Users/node_modules', '/node_modules' ] }, extensions: [Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] }, cache: [Object: null prototype] { '/Users/bjhl/Documents/webpackSource/index.js': Module { id: '.', exports: {}, parent: null, filename: '/Users/bjhl/Documents/webpackSource/index.js', loaded: false, children: [], paths: [Array] } } }
require function static attributes
will be added in detail later.
require use
You can see the following instructions about require in the official website documentation:
require(id)# Added in: v0.1.13 id module name or path Returns: exported module content Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory.
At the same time, three methods of using require are also given:
// Importing a local module: const myLocalModule = require('./path/myLocalModule'); // Importing a JSON file: const jsonData = require('./path/filename.json'); // Importing a module from node_modules or Node.js built-in module: const crypto = require('crypto');
From the above documents, the following information can be drawn:
require accepts one parameter, The formal parameter is named id and its type is String.
The require function returns the contents of the module, and the type is arbitrary.
The require function can import modules, JSON files, and local files. Modules can be exported from node_modules, local modules, JSON files via a relative path against the __dirname variable (if defined) or the current working directory.
require practice
Here we will discuss the practical conclusions of require in categories.
requireImport JSON
JSON is a syntax for serializing objects, arrays, numbers, strings, Boolean values, and null .
At the beginning of the article, it was mentioned that the version attribute in the package.json file is read through the require("./package.json") file. Here we will try to import the info.json file and view related information.
The file structure directory is as follows:
. ├── index.js └── info.json
Modify the content of the info.json file to:
{ "name": "myInfo", "hasFriend": true, "salary": null, "version": "v1.0.0", "author": { "nickname": "Hello Kitty", "age": 20, "friends": [ { "nickname": "snowy", "age": 999 } ] } }
In info.json, it contains strings, Boolean values, and null , numbers, objects and arrays.
Modify the content of index.js as follows and run the command node index.js in the current terminal, and get the following results:
const info = require("./info.json") console.log(Object.prototype.toString.call(info)) // [object Object] console.log(info.version) // v1.0.0 console.log(info.hasFriend) // true console.log(info.salary) // null console.log(info.author.nickname) // Hello Kitty console.log(info.author.friends) // [ { nickname: 'snowy', age: 999 } ]
As you can see, when require imports a JSON file, it returns An object, Nodejs can directly access all properties in this object, including String, Boolean, Number, Null, Object, and Array. My personal guess is that a method similar to JSON.parse() may be used here.
Through this conclusion, we also came up with an idea, which is to pass in the JSON file through the require method to read certain values. For example, at the beginning of the article, webpack obtained the version value by reading the package.json file. .
requireImport local js files
The file structure directory is as follows:
. ├── index.js ├── module_a.js └── module_b.js
In the index.js file, module_a is imported in order and module_b and assign values, and then print these two variables, the content is as follows:
console.log("*** index.js开始执行 ***") const module_a = require("./module_a") const module_b = require("./module_b") console.log(module_a, "*** 打印module_a ***") console.log(module_b, "*** 打印module_b ***") console.log("*** index.js结束执行 ***")
In the module_a file, module.exports or exports is not specified, but an asynchronous execution statement setTimeout is added, the content is as follows:
In theconsole.log("** module_a开始执行 **") let name = "I'm module_a" setTimeout(() => { console.log(name, "** setTimeout打印a的名字 **") }, 0) console.log("** module_a结束执行 **")
module_b file, module.exports is specified (you can also change it to exports.name, but you cannot directly use exports to equal an object, because exports and module.exports actually point to an address and reference the same object , if exports is equal to other reference types, it will no longer point to module.exports, and the content in module.exports cannot be changed), the content is as follows:
console.log("** module_b开始执行 **") let name = "I'm module_b" console.log(name, "** 打印b的名字 **") module.exports = { name } console.log("** module_b结束执行 **")
Run node index.js in the current directory terminal and get The following output:
*** index.js开始执行 ***
** module_a开始执行 **
** module_a结束执行 **
** module_b开始执行 **
I am module_b ** 打印b的名字 **
** module_b结束执行 **
{} '*** 打印module_a ***'
{ name: 'I am module_b' } '*** 打印module_b ***'
*** index.js结束执行 ***
I am module_a ** setTimeout打印a的名字 **
通过以上执行结果可以得出结论:
require某个js文件时,如果未通过exports或者module.exports指定导出内容,则require返回的结果是一个空对象;反之可以通过module.export或者给exports属性赋值来导出指定内容。
require某个js文件时,该文件会立即sync执行。
require导入模块
我们先选择一个npm包——cors。 进入文件夹,运行一下命令:
npm init -y // 初始化 echo -e "let cors = require(\"cors\")\nconsole.log(cors)" > index.js // 生成index.js文件 npm install cors --save // 安装cors包
文件结构如下(...处省略了其他的模块):
. ├── index.js ├── node_modules │ ├── cors │ │ ├── CONTRIBUTING.md │ │ ├── HISTORY.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── lib │ │ │ └── index.js │ │ └── package.json │ │ ... ├── package-lock.json └── package.json
index.js中的内容如下:
let cors = require("cors") console.log(cors)
运行 node index.js ,得出以下结果:
[Function: middlewareWrapper]
找到node_modules下的cors模块文件夹,观察cros模块中的package.json文件,找到main字段: "main": "./lib/index.js" ,找到main字段指向的文件,发现这是一个IIFE,在IIFE中的代码中添加,console.log("hello cors"),模拟代码结构如下:
(function () { 'use strict'; console.log("hello cors"); // 这是手动添加的代码 ... function middlewareWrapper(o) { ... } module.exports = middlewareWrapper; })()
再次运行 node index.js ,得出以下结果:
hello cors
[Function: middlewareWrapper]
为什么会打印出 hello cors 呢?因为require模块的时候,引入的是该模块package.json文件中main字段指向的文件。而这个js文件会自动执行,跟require引用本地js文件是相同的。
packjson文档
在npm的官方网站中可以找到关于package.json中的main字段定义。
main The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned. This should be a module ID relative to the root of your package folder For most modules, it makes the most sense to have a main script and often not much else.
在以上说明中可以得出以下结论:
main字段是一个模块ID,是程序的主入口。
当使用require("xxx")的时候,导入的是main字段对应的js文件里的module.exports。
所以require导入模块的时候,是运行的对应模块package.json中main字段指定的文件。
推荐学习:《node视频教程》
The above is the detailed content of node require what does it mean. 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

AI Hentai Generator
Generate AI Hentai for free.

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 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.

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

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.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

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.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
