You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
46 Min
46 Seg
Curso de Fundamentos de Node.js

Curso de Fundamentos de Node.js

Oscar Barajas Tavares

Oscar Barajas Tavares

M贸dulo Process: manejo de procesos en Node.js

15/20
Resources

Process management in Node.js is fundamental to develop robust and efficient applications. The process module provides us with valuable information and control over the running process, allowing us to create smarter scripts that are adaptable to different environments. Mastering this module is essential for any developer looking to take full advantage of Node.js capabilities.

What is the process module and why is it important?

The process module is one of the most important modules in Node.js, as it provides information and control over the running process. This global module allows us to access system information, handle process events, control standard input and output, and much more.

To begin exploring this module, let's create a file called process.js and see some of its basic functionality:

console.log("Process ID:", process.pid);console.log("Current directory:", process.cwd());console.log("Node version:", process.version);

When executing this code, we will obtain information such as:

  • The process ID (PID)
  • The current working directory
  • The version of Node.js we are using.

In addition, we can access information about the platform, architecture and runtime:

console.log("Platform:", process.platform);console.log("Architecture:", process.arch);

This information is extremely useful for creating scripts that behave differently depending on the environment in which they are executed.

How to access environment variables?

One of the most used functionalities of the process module is the access to environment variables through process.env. This allows us to store sensitive information outside our code:

console.log(process.env); // Display all environment variablesconsole.log("PATH:", process.env.PATH);console.log("USER PROFILE:", process.env.USER_PROFILE);console.log("NODE_ENV:", process.env.NODE_ENV || "Not defined");

Environment variables are essential for configuring applications in different environments (development, test, production) without changing the code.

How to monitor memory usage?

The process module also allows us to monitor the memory usage of our application:

const memory = process.memoryUsage();console.log(memory);

This code will show us detailed information about memory usage, including:

  • rss: Resident Set Size (amount of memory allocated in RAM)
  • heapTotal: Total memory of the heap
  • heapUsed: Used memory of the heap
  • external: Memory used by objects external to V8
  • arrayBuffers: Memory used by ArrayBuffers

How to handle process events?

The process module allows us to listen and respond to different process events, such as process termination or interrupt signals.

Exit event

We can execute code when the process is about to terminate:

process.on('exit', (code) => { console.log("The process is finished", code);});

Interrupt signals

We can also capture interrupt signals (such as Ctrl+C) and perform actions before the process terminates:

process.on('SIGINT', () => { console.log("Interrupt signal was received"); // Clean up resources, close connections, etc. process.exit(0);});

Handling these events is crucial to ensure that our applications close correctly, freeing resources and completing pending tasks.

How to interact with the user through the console?

The process module allows us to interact with the user through the standard input(stdin):

console.log("Type something and press Enter or Control+C to exit");
process.stdin.on('data', (data) => { const input = data.toString().trim();  
 if (input.toLowerCase() === 'exit') { console.log("Output command received"); process.exit(); } else { console.log("You typed:", input); console.log("Type 'exit' to finish or type something else"); } } });

This code creates a simple interface where:

  1. The user can type text into the console.
  2. If he types "exit", the program terminates
  3. If he types anything else, the program displays the text and continues waiting for input.

This functionality is perfect for creating interactive command line tools or scripts that require user input.

The process module is a powerful tool in the arsenal of any Node.js developer. Mastering its functionalities will allow you to create more robust, secure and adaptable applications for different environments. I invite you to experiment with the examples presented and share your own implementations in the comments section.

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

comparto la soluci贸n al reto de convertir bytes a megabytes en el sistema num茅rico decimal ![](https://static.platzi.com/media/user_upload/image-6dadbea8-a327-43b5-bf6d-0c60f319a011.jpg) ```js function convertBytesToMegaBytes(bytes){ megabytes = bytes * 0.000001; return megabytes; } const memoryUsage = process.memoryUsage(); console.table(memoryUsage); for (let [key, value] of Object.entries(memoryUsage)) { console.log(`${key}: ${convertBytesToMegaBytes(value)} MB`); } ```*function* convertBytesToMegaBytes(*bytes*){聽 聽 megabytes = bytes \* 0.000001;聽 聽 return megabytes;} *const* memoryUsage = process.memoryUsage();console.table(memoryUsage); for (*let* \[key, value] of Object.entries(memoryUsage)) {聽 聽 console.log(`${key}: ${convertBytesToMegaBytes(value)} MB`);}
En el examen viene esta pregunta... ![](https://static.platzi.com/media/user_upload/upload-49335933-aebe-4777-a5f7-e2204d751e9a.png) Esto es correcto?![]()
Respuesta al reto: ```js const processInfo = { Path: process.env.PATH, Home: process.env.HOME, User: process.env.USER, NodeVersion: process.versions.NODE_ENV || 'No disponible', MemoryUsage: getMemoryUsageInfo() }; console.log('Informaci贸n del proceso:', processInfo); function getMemoryUsageInfo() { const response = { rss: process.memoryUsage().rss, heapTotal: process.memoryUsage().heapTotal, heapUsed: process.memoryUsage().heapUsed, external: process.memoryUsage().external, }; for (const key in response) { response[key] = (response[key] / 1024 / 1024).toFixed(2) + ' MB'; } return response; } ```
Soluci贸n al reto: ```js const memoryUsage = process.memoryUsage(); for (const key in memoryUsage) { // Convertimos el valor de bytes a megabytes en dos pasos: // 1. De bytes a kilobytes: bytes / 1024 // 2. De kilobytes a megabytes: kilobytes / 1024 // Resultado final: bytes / 1024 / 1024 console.log(`${key}: ${(memoryUsage[key] / 1024 / 1024).toFixed(2)} MB`); } ```
As铆 resolv铆 el reto propuesto en clase ```js //Cantidad de memoria usada en el proceso const memoryUsage = process.memoryUsage() console.table(memoryUsage) //Conversi贸n de la cantidad de memoria a MB const memoryUsageConverted = { 'rss': memoryUsage['rss']* 0.000001, 'heapTotal': memoryUsage['heapTotal'] * 0.000001, 'heapUsed': memoryUsage['heapUsed']* 0.000001, 'external': memoryUsage['external']* 0.000001, 'arrayBuffers': memoryUsage['arrayBuffers']* 0.000001 } console.table(memoryUsageConverted) ```