Process模块 (Features of Process)

process is a global variable which indicates the current Node.js process.

It is actually an instance of EventEmiter, which is used to subscribe events and emit messages to specific events, for more information, you may refer to offical docs.

'process' includes several common used features, we will have an outline below.

process.argv

process.argv returns an array containing the command line arguments, it's quite useful when we need to identify some special conditions.

We firstly create a file below and run it in the command line:

const {argv} = process;

argv.forEach((value, index) => {
console.log(`${index}: ${value}`);
});
$ node argv.js test name=scott --dev

The code will demonstrates how we obtain the actual arguments from command line:

0: /usr/local/bin/node
1: /Users/scott/process/argv.js
2: test
3: name=scott
4: --dev

The first element indicates the absolute pathname of the executable that started the Node.js process, it's identical to process.execPath. And the second one is the absolute pathname of JavaScript file being executed. For the rest, they are additional command line arguments.

process.execArgv

process.execArgv will hold the set of Node.js-specific command-line options passed when the Node.js process was launched. These options are useful in order to spawn child processes with the same execution environment as the parent, and they are prior to the JavaScript file in command line:

$ node --harmony script.js --version

Results in 'process.execArgv':

['--harmony']

process.nextTick(callback[, ...args])

The process.nextTick() method adds the callback to the 'next tick queue'. Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.

This is not a simple alias to 'setTimeout(fn, 0)'. It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.

It should be noted that, the next tick queue is completely drained on each pass of the event loop before additional I/O is processed. As a result, recursively setting nextTick() callbacks will block any I/O from happening, just like a 'while(true);' loop.

process.exit([code]);

process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code '0' or the value of 'process.exitCode' if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.

Calling 'process.exit()' will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to 'process.stdout' and 'process.stderr'.

In most situations, it is not actually necessary to call 'process.exit()' explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The 'process.exitCode' property can be set to tell the process which exit code to use when the process exits gracefully.

Note that, Calling 'process.exit()' will force the process to exit before some asynchronous work can be performed, so rather than calling 'process.exit()' directly, the code should set the 'process.exitCode' and allow the process to exit naturally by avoiding scheduling any additional work for the event loop.

If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling 'process.exit()'.

Event: 'exit'

The exit event is emitted when the Node.js process is about to exit as a result of either:

  • The process.exit() method being called explicitly;

  • The Node.js event loop no longer having any additional work to perform.

There is no way to prevent the exiting of the event loop at this point, and once all 'exit' listeners have finished running the Node.js process will terminate.

The listener callback function is invoked with the exit code specified either by the 'process.exitCode' property, or the exitCode argument passed to the 'process.exit()' method.

Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:

process.on('exit', code => {
setTimeout(() => {
console.log('This will not run');
}, 0); console.log(`About to exit with code: ${code}`);
});

Event: 'beforeExit'

The beforeExit event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

The listener callback function is invoked with the value of 'process.exitCode' passed as the only argument, let's take this code for an example:

process.on('beforeExit', code => {
console.log(`beforeExist invoked, code: ${code}`);
}); process.exitCode = 1;

The command-line message will be:

beforeExist invoked, code: 1

Note that, The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling 'process.exit()' or uncaught exceptions, the following two event handlers will not get a chance to run:

process.on('beforeExit', code => {
console.log(`beforeExist invoked, code: ${code}`);
}); process.exit();
process.on('beforeExit', code => {
console.log(`beforeExist invoked, code: ${code}`);
}); callNonExistentFunc();

'beforeExit' will be prior to 'exit' event, the following code shows the invocation order:

process.on('beforeExit', code => {
console.log(`beforeExist invoked, code: ${code}`);
}); process.on('exit', (code) => {
setTimeout(() => {
console.log('This will not run');
}, 0); console.log(`About to exit with code: ${code}`);
}); // beforeExist invoked, code: 0
// About to exit with code: 0

Event: 'uncaughtException'

In above code, calling an nonexistent function will cause an exception, by default, Node.js will print the stack trace to stderr and exit the current process. Adding a 'uncaughtException' handler will override this default behavior. The 'uncaughtException' event will be emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. And the handler function is called with the 'Error' object passed as the only argument.

process.on('uncaughtException', err => {
console.log(`Caught exception: ${err}`);
process.exitCode = 1;
}); process.on('beforeExit', code => {
console.log(`beforeExist invoked, code: ${code}`);
}); setTimeout(() => {
console.log('This will still run.');
}, 500); callNonexistentFunc(); console.log('This will not run.');

Run this code, we will get the messages below:

Caught exception: ReferenceError: callNonexistentFunc is not defined
This will still run.
beforeExist invoked, code: 1

Note that 'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to 'On Error Resume Next'. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.

Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion.

Attempting to resume normally after an uncaught exception can be similar to pulling out of the power cord when upgrading a computer — nine out of ten times nothing happens - but the 10th time, the system becomes corrupted.

The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after 'uncaughtException'.

To restart a crashed application in a more reliable way, whether 'uncaughtException' is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed.

Node: Process模块 (Features of Process)的更多相关文章

  1. Node.js process 模块常用属性和方法

    Node.js是常用的Javascript运行环境,本文和大家发分享的主要是Node.js中process 模块的常用属性和方法,希望通过本文的分享,对大家学习Node.js http://www.m ...

  2. Node.js的process模块

    process模块用来与当前进程互动,可以通过全局变量process访问,不必使用require命令加载.它是一个EventEmitter对象的实例. 属性 process对象提供一系列属性,用于返回 ...

  3. Node.js之process模块

    注意⚠️:process为nodejs内置对象,不需要实例化,改模块用来与当前进程进行互动,可以通过全局变量process访问,它是一个EventEmitter对象的实例. process对象提供一系 ...

  4. node中非常重要的process对象,Child Process模块

    node中非常重要的process对象,Child Process模块Child Process模块http://javascript.ruanyifeng.com/nodejs/child-proc ...

  5. Node.js进程管理之Process模块

    在前面Node.js事件运行机制也有提到,Node.js应用在单个线程运行,但是现在大部分服务器都是多处理器,为了方便使用多个进程,Node.js提供了3个模块.Process模块提供了访问正在运行的 ...

  6. nodejs笔记一--模块,全局process对象;

    一.os模块可提供操作系统的一些基本信息,它的一些常用方法如下: var os = require("os"); var result = os.platform(); //查看操 ...

  7. [Node.js] 06 - Multi-thread and process module

    课前阅读:关于Node.js后端架构的一点后知后觉 书推荐:<Node.js design patterns> 衍生问题: 微服务的必要性,Flux架构 容错性和拓展性 一.立体拓展 假设 ...

  8. Node.js中环境变量process.env详解

    Node.js中环境变量process.env详解process | Node.js API 文档http://nodejs.cn/api/process.html官方解释:process 对象是一个 ...

  9. [转]nodejs中的process模块--child_process.exec

    1.process是一个全局进程,你可以直接通过process变量直接访问它. process实现了EventEmitter接口,exit方法会在当进程退出的时候执行.因为进程退出之后将不再执行事件循 ...

随机推荐

  1. Redis (error) NOAUTH Authentication required.

    首先查看redis设置密码没 127.0.0.1:6379> config get requirepass 1) "requirepass" 2) "" ...

  2. 【GMT43智能液晶模块】例程二十一:DMA LAN实验——高速数据传输测速

    源代码下载链接: 链接:https://pan.baidu.com/s/1wQomZvOUP9_ZslZus_NSIA 提取码:3fmf 复制这段内容后打开百度网盘手机App,操作更方便哦 GMT43 ...

  3. windows下安装zk

    1 下载安装包并解压 2 修改conf下配置文件名字 zoo_sample.cfg 文件名改为 zoo.cfg 3 启动zk zKServer.cmd 4启动客户端连接测试 zKCli.cmd 127 ...

  4. PHP $$符号的作用与使用方法

    php中$$符号的定义与作用 在PHP中单个美元符号变量($str),表示一个名为str的普通变量,它可以存储字符串.整数.数组.布尔等任何类型的值. 双美元符号的变量($$str):表示一个可变变量 ...

  5. IDEA中类文件显示J,IDEA Unable to import maven project: See logs for details

    今天用了下lemon清理了下垃圾后,IDEA打开项目类文件图标由C变为J,在IDEA右侧的Maven Project中点击刷新提示IDEA Unable to import maven project ...

  6. Dockerfile语法梳理

    Dockerfile语法 我们先来看一下上篇的 Dockerfile #获取base image FROM adoptopenjdk/openjdk8:latest #类似于执行 linux指令 RU ...

  7. java 正则 replace 忽略大小写

    String description = model.getDescription(); if (!"".equals(description)) { //replace(/\&l ...

  8. WIFI-Direct(Wifi直连)、AirPlay、DLAN、Miracast功能介绍

    不知道大家对无线同屏技术有多少了解,当这种技术普及的时候,我想我们的工作与生活又会方便很多吧!下面是目前三种主流同屏技术的介绍: 目前这种将终端信号经由WiFi传输到电视.电视盒的技术有三种:DLNA ...

  9. vs2017- C语言- winsocket- 链接错误 LNK2019

    错误介绍 操作系统:windows10 IDE:vs2017 语言:C语言 项目内容简介:编写一个双人网络海战棋对战游戏 错误类型:链接错误 LNK2019 解决方案:程序需要用到ws2_32.lib ...

  10. ZYNQ笔记(0):C语言基础知识复习

    ZYNQ的SDK是用C语言进行开发的,C语言可以说是当今理工类大学生的必备技能.我本科学C语言时就是对付考试而已,导致现在学ZYNQ是一脸懵逼.现在特开一帖,整理一下C语言的基础知识. 一.定义 1. ...