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

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.