DEV Community

WangLiwen
WangLiwen

Posted on

Change process priority, Nodejs os.setPriority() method

os.setPriority() is a built-in application programming interface of the os module, available in nodejs versions after v10.10, which is used to set the scheduling priority of a process specified by pid and priority.

Syntax:
os.setPriority(pid, priority)
Parameters: This method has two parameters, as described below:
pid: This is an optional parameter. It specifies the process ID of the process whose scheduling priority is to be set. Its default value is 0.
priority: This is a required parameter. It specifies the priority to be set for the process with the specified process ID. The value of this parameter must be between -20 (highest) and 19 (lowest).
Note: -20 is the highest priority, and 19 is the lowest priority.
Return value: This method does not return any value.
Note: Since the priority in the Windows system is different from that in the UNIX system, the priority in the Windows system is mapped to one of the six priority constants in os.constants.priority. Therefore, the retrieved value may be slightly different from the actual value. In the Windows system, setting the highest priority requires elevating user permissions. Therefore, sometimes PRIORITY_HIGHEST may be changed to PRIORITY_HIGH without any warning.

The following example demonstrates how to use os.setPriority() in Node.js:

// Node.js program to demonstrate the    
// os.setPriority() Method 
  
// Allocating os module 
const os = require('os'); 
  
// Setting priority for the current process 
os.setPriority(17); 
  
try{ 
     
    console.log(process.pid);
    os.setPriority(19);
    // Printing priority of current process
    console.log(os.getPriority()); 
}catch(err){ 
    // Printing error message 
    console.log(": error occurred"+err); 
} 

Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)