Processes exist on global objects and can be used without requiring a require() load. The process module does two main things

  • Get process information (resource usage, running environment, running state)
  • Perform process operations (listen for events, schedule tasks, issue warnings)

Resource use

Resource usage refers to the machine resources consumed by running this process. For example, memory and CPU

memory

process.memoryUsage())

{ rss: 21848064,
  heapTotal: 7159808,
  heapUsed: 4431688,
  external: 8224 
 }
Copy the code

The composition of RSS (resident memory) is shown below

The code segment corresponds to the currently running code

External corresponds to the memory footprint of C++ objects (bound to V8 managed JS objects), such as the use of Buffer

Buffer.allocUnsafe(1024 * 1024 * 1000);
console.log(process.memoryUsage());

{ rss: 22052864,
  heapTotal: 6635520,
  heapUsed: 4161376,
  external: 1048584224 }
Copy the code

cpu

const startUsage = process.cpuUsage();
console.log(startUsage);

const now = Date.now();
while(Date.now() - now < 500); console.log(process.cpuUsage()); console.log(process.cpuUsage(startUsage)); // {user: 59459, system: 18966} // {user: 558135, system: 22312}Copy the code

User indicates the user time, and system indicates the system time

Runtime environment

The running environment refers to the host environment in which the process runs, including the running directory, Node environment, CPU architecture, user environment, and system platform

Run directory

console.log(`Current directory: ${process.cwd()}`);

// Current directory: /Users/xxxx/workspace/learn/node-basic/process
Copy the code

The node environment

The console. The log (process. Version) / / v9.1.0Copy the code

If you want not only node version information, but also v8, Zlib, libuv version information, you need to use process.versions

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

The CPU architecture

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

// This processor architecture is x64
Copy the code

Support values include: ‘arm’ and ‘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

Copy the code

Process. env can also obtain other user environment information (such as PATH, SHELL, HOME, etc.) in addition to the custom information at startup, if you are interested, you can print it yourself

The system platform

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

This platform is darwin
Copy the code

Supported system platforms include: ‘AIX’ ‘Darwin’ ‘FreeBSD’ ‘Linux’ ‘OpenBSD’ ‘Sunos” Win32 ‘

Android is still experimental

Running state

Running status Indicates the running information of the current process, including startup parameters, execution directory, main file, PID information, and running time

Launch parameters

There are three methods for obtaining startup parameters. ExecArgv obtains command line options for Node.js (see documentation on the official website)

Argv gets information about non-command-line options, and 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 // Output result ['/ Users/xiji /. NVM/versions/node/v9.1.0 / bin/node'.'/Users/xiji/workspace/learn/node-basic/process/b.js'.'foo=bar'.'--version' ]
node
[ '--harmony' ]
Copy the code

Perform directory

console.log(process.execPath); / / / Users/XXXX/NVM/versions/node/v9.1.0 / bin/nodeCopy the code

The elapsed time

var date = new Date();
while(new Date() - date < 500) {} console.log(process.uptime()); / / 0.569Copy the code

Master file

In addition to require.main, you can also use process.mainModule to determine if a module is the main file

//a.js
console.log(`module A: ${process.mainModule === module}`);

//b.js
require('./a');
console.log(`module B: ${process.mainModule === module}`); Node b.js // output module A:false
module B: true
Copy the code

PID information

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

Listen for an event

Process is an instance object of EventEmiiter, so you can use process.on(‘eventName’, () => {}) to listen for events. There are two common event types:

  • Process states such as: beforeExit, exit, uncaughtException, message
  • Signal events such as SIGTERM, SIGKILL, and SIGUSR1

BeforeExit differs from exit in two ways:

  • BeforeExit can execute asynchronous code, exit must be synchronous code
  • Calling process.exit() manually or triggering an uncaptException causing the process to exit does not trigger the beforeExit event, but the exit event does.

Therefore, none of the following code console will 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();
Copy the code

‘uncaughtException’ is finally emitted when the exception is not caught and handled. By default, Node.js prints stack information to stderr and exits the process. Do not try to prevent uncaughtException from leaving the process, so the state of the program may be unstable at this point. The recommended method is to catch and handle errors in the code as soon as possible. UncaughtException does some cleanup.

Note: the 9.3 version of the node increased process. SetUncaughtExceptionCaptureCallback method

When the process. SetUncaughtExceptionCaptureCallback (fn) specifies the surveillance function, uncaughtException events will no longer be triggered.

process.on('uncaughtException'.function() {
  console.log('uncaught listener');
});

process.setUncaughtExceptionCaptureCallback(function() {
  console.log('uncaught fn');
});

a.b();
// uncaught fn
Copy the code

Message is used to send messages between parent and child processes. For details on how to create a parent process, see the child_process module.

Unlike SIGKILL, which is also used to request the termination of a Node.js process, the SIGTERM signal can choose to respond or ignore it. SIGTERM terminates a process in a friendly manner by releasing allocated resources (such as database connections) before the process terminates. This method is called graceful shutdown.

  • Application is notified that it needs to be closed (SIGTERM signal is received)
  • The application notifies the load balancer that no new requests are received
  • The application completes the request in progress
  • Releasing resources (such as database connections)
  • The application exits normally. The exit status code is 0

SIGUSR1 node.js launches the built-in debugger when SIGUSR1 is received, when the following operations are performed

kill -USR1 PID_OF_THE_NODE_JS_PROCESS
Copy the code

You can see that Node.js launches the debugger agent on port 9229

Server is listening 8089 Debugger listening on the ws: / / 127.0.0.1:9229/7 ef98ccb - 02 fa - 451 - a - 8954-4706 bd74105f Forhelp, see: https://nodejs.org/en/docs/inspector
Copy the code

You can also use –inspect to start the debug agent when the service starts

node --inspect index.js
Copy the code

Scheduling tasks

process.nextTick(fn)

The tasks scheduled by process.nextTick are asynchronous tasks. EventLoop is divided into stages, and specific tasks are executed in each stage, while nextTick tasks will be executed when phases are switched. EventLoop is shown below, and will be explained in more detail later

A warning

process.emitWarning('Something warning happened! ', {
  code: 'MY_WARNING'.type: 'XXXX'
});

// (node:14771) [MY_WARNING] XXXX: Something warning happened!
Copy the code

When type is DeprecationWarning, you can influence it with a command-line option

  • --throw-deprecationWill throw an exception
  • --no-deprecationNo output DeprecationWarning
  • --trace-deprecationPrints detailed stack information
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
Copy the code

The resources

Blog.risingstack.com/mastering-t…