search
HomeWeb Front-endJS TutorialDetailed explanation of the use of Node.js notes process module

This time I will bring you a detailed explanation of the use of the Node.js note process module. What are the precautions when using the Node.js note process module. The following is a practical case, let's take a look.

process exists on the global object and can be used without using require() to load it. The process module mainly does two things

  1. Read: Get process information (resource usage, operating environment, operating status)

  2. Write: Perform process operations (listen to events, schedule tasks, issue warnings) Resource usage

Resource usage

refers to the machine resources consumed by running this process. For example, the composition of memory and cpu

memory

process.memoryUsage())
{ rss: 21848064,
 heapTotal: 7159808,
 heapUsed: 4431688,
 external: 8224 
 }

rss (resident memory) is shown in the figure below

The code segment corresponds to the currently running code

external corresponds to the memory occupied by the C object (bound to the JS object managed by V8), such as the use of Buffer

Buffer.allocUnsafe(1024 * 1024 * 1000);
console.log(process.memoryUsage());
{ rss: 22052864,
 heapTotal: 6635520,
 heapUsed: 4161376,
 external: 1048584224 }

cpu

const startUsage = process.cpuUsage();
console.log(startUsage);
const now = Date.now();
while (Date.now() - now <p style="text-align: left;">user corresponds to the user time, system represents the system time </p><p style="text-align: left;"><span style="color: #ff0000"><strong>Running environment </strong></span></p><p style="text-align: left;">The running environment refers to the running of this process The host environment includes the running directory, node environment, CPU architecture, user environment, and system platform</p><p style="text-align: left;"><strong>Running directory</strong></p><pre class="brush:php;toolbar:false">const startUsage = process.cpuUsage();
console.log(startUsage);
const now = Date.now();
while (Date.now() - now <p style="text-align: left"><strong>node environment</strong></p> <pre class="brush:php;toolbar:false">console.log(process.version)
// v9.1.0

If you not only want to get the node version information, but also want v8, zlib, libuv version and other information, you need to use process.versions

console.log(process.versions);
{ http_parser: '2.7.0',
 node: '9.1.0',
 v8: '6.2.414.32-node.8',
 uv: '1.15.0',
 zlib: '1.2.11',
 ares: '1.13.0',
 modules: '59',
 nghttp2: '1.25.0',
 openssl: '1.0.2m',
 icu: '59.1',
 unicode: '9.0',
 cldr: '31.0.1',
 tz: '2017b' }

cpu architecture

console.log(`This processor architecture is ${process.arch}`);
// This processor architecture is x64

Supported values ​​include: 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' 'x64'

User environment

console.log(process.env.NODE_ENV); // dev
NODE_ENV=dev node b.js

In addition to custom information at startup, process.env can also obtain other User environment information (such as PATH, SHELL, HOME, etc.), if you are interested, you can print it yourself and try it

System platform

console.log(`This platform is ${process.platform}`);
This platform is darwin

Supported system platforms include:'aix' 'darwin' 'freebsd' 'linux' 'openbsd' 'sunos' 'win32'

android is still in the experimental stage

Running status

The running status refers to the information related to the running of the current process, including startup Parameters, execution directory, main file, PID information, running time

Startup parameters

There are three ways to obtain startup parameters. execArgv obtains the command line options of Node.js ( See official website documentation)

argv gets the information of non-command line options, argv0 gets the value of argv[0] (slightly different)

console.log(process.argv)
console.log(process.argv0)
console.log(process.execArgv)
node --harmony b.js foo=bar --version
// 输出结果
[ '/Users/xiji/.nvm/versions/node/v9.1.0/bin/node',
 '/Users/xiji/workspace/learn/node-basic/process/b.js',
 'foo=bar',
 '--version' ]
node
[ '--harmony' ]

Execution directory

console.log(process.execPath);
// /Users/xxxx/.nvm/versions/node/v9.1.0/bin/node

Run Time

var date = new Date();
while(new Date() - date <p style="text-align: left">Main file</p><p style="text-align: left;">In addition to require.main, you can also use process.mainModule to determine whether a module is the main file</p><pre class="brush:php;toolbar:false">//a.js
console.log(`module A: ${process.mainModule === module}`);
//b.js
require('./a');
console.log(`module B: ${process.mainModule === module}`);
node b.js
// 输出
module A: false
module B: true

PID information

console.log(`This process is pid ${process.pid}`); //This process is pid 12554

Listening events

Commonly used events include beforeExit, exit, uncaughtException, message

beforeExit and exit There are two differences:

  1. beforeExit can execute asynchronous code, exit can only be synchronous code

  2. code manually calls process.exit() Or triggering uncaptException and causing the process to exit will not trigger the beforeExit event, but the exit event will be triggered.

So the following code console will not be executed

process.on('beforeExit', function(code) {
 console.log('before exit: '+ code);
});
process.on('exit', function(code) {
 setTimeout(function() {
  console.log('exit: ' + code);
 }, 0);
});
a.b();

当异常一直没有被捕获处理的话,最后就会触发'uncaughtException'事件。默认情况下,Node.js会打印堆栈信息到stderr然后退出进程。不要试图阻止uncaughtException退出进程,因此此时程序的状态可能已经不稳定了,建议的方式是及时捕获处理代码中的错误,uncaughtException里面只做一些清理工作(可以执行异步代码)。

注意:node的9.3版本增加了process.setUncaughtExceptionCaptureCallback方法

当process.setUncaughtExceptionCaptureCallback(fn)指定了监听函数的时候,uncaughtException事件将会不再被触发。

process.on('uncaughtException', function() {
 console.log('uncaught listener');
});
process.setUncaughtExceptionCaptureCallback(function() {
 console.log('uncaught fn');
});
a.b();
// uncaught fn

message适用于父子进程之间发送消息,关于如何创建父子进程会放在child_process模块中进行。

调度任务

process.nextTick(fn)

通过process.nextTick调度的任务是异步任务,EventLoop是分阶段的,每个阶段执行特定的任务,而nextTick的任务在阶段切换的时候就会执行,因此nextTick会比setTimeout(fn, 0)更快的执行,关于EventLoop见下图,后面会做进一步详细的讲解

发出警告

process.emitWarning('Something warning happened!', {
 code: 'MY_WARNING',
 type: 'XXXX'
});
// (node:14771) [MY_WARNING] XXXX: Something warning happened!

当type为DeprecationWarning时,可以通过命令行选项施加影响

  1. --throw-deprecation抛出异常

  2. --no-deprecation 不输出DeprecationWarning

  3. --trace-deprecation 打印详细堆栈信息

process.emitWarning('Something warning happened!', {
 type: 'DeprecationWarning'
});
console.log(4);
node --throw-deprecation index.js
node --no-deprecation index.js
node --trace-deprecation index.js

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎么使用webpack3.0配置webpack-dev-server

JS反射与依赖注入使用案例分析

The above is the detailed content of Detailed explanation of the use of Node.js notes process module. For more information, please follow other related articles on the PHP Chinese website!

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

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software